How does Django serve media files? How does Django serve media files? django django

How does Django serve media files?


FOR DEVELOPMENT ONLY

You can setup a static media server for use with their development server by doing this in your urls.py file. I have attached the code showing how I use it (along with the forced DEBUG conditionals.)

from django.conf import settingsfrom django.conf.urls.defaults import *      # Uncomment the next two lines to enable the admin:from django.contrib import adminadmin.autodiscover()urlpatterns = patterns('',     (r'^$', 'views.index'),                # Accounts    (r'^accounts/login/$', 'views.user_login'),    (r'^accounts/logout/$', 'views.user_logout'),    # Contrib Modules    (r'^admin/(.*)', admin.site.root),)if settings.DEBUG :    urlpatterns += patterns('',        (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),    )

I place my MEDIA_ROOT in a subdirectory of html/media and link to it as such in settings.py

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'html/media/').replace('\\','/')

After development is finished, the project gets deployed to the web server where static media files are then served by Apache using directives.


Serving static content from Django is discouraged from the developer themselves (if I'm not wrong, it only works when in debug mode). You should use a dedicated web server, instead.

If you really need to do that, anyway, read the documentation on how to serve static files.


This is the correct way of showing image files with ImageField. Imagine we have a user profile picture:

models.py:

UserProfile:    profilePic= models.ImageField( upload_to='PATH_TO_UPLOAD', blank=True, null=True)

settings.py:

MEDIA_ROOT = 'FULL_PATH_OF_MEDIA'MEDIA_URL = 'URL_OF_MEDIA'

urls.py:

urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

PATH_TO_UPLOAD is the path which user upload data goes. This is sub-directory of FULL_PATH_OF_MEDIA, which means the uploaded file will have

FULL_PATH_OF_MEDIA/PATH_TO_UPLOAD 

full path.Now this content can be accessed at this url:

SITE_NAME/URL_OF_MEDIA/PATH_TO_UPLOAD

I also recommend reading this on static_files vs media_files

doc