Handling Media Files in Django
In Django, Files which are uploaded by the user are called Media or Media Files. Here are some examples:
1. A user uploaded image, pdfs, doc files etc while publishing a post, these files are Media files.
2. Images of products in an e-commerce site.
3. User's profile image.
Just as with static files, to serve media files we have do add some configurations in our
Media Files Configurations
Media files depends upon two configurations:
None of these are set by default.
It contains the absolute path to the file system where Media files will be uploaded. It accepts a string not a list or tuple.
Create a new directory named
media inside Django project root directory i.e the same place where
manage.py is located.
settings.py file and add the following code to the end of the file, just below
STATICFILES_DIRS (which we had set earlier).
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Works similar to
STATIC_URL, but instead used to access media files. Just below the
MEDIA_ROOT setting add the following code to the end of
MEDIA_URL = '/media/'
At this point, if you try accessing the file, you would get a 404 error. Why ?
The problem is that Django development server don't serve media files by default. To make Django development server serve static we have to add a url pattern in sitewide
urls.py in the Django project configuration directory, i.e
TGDB/django_project/django_project. If you are following along this tutorial closely, your
urls.py file should look like this:
from django.conf.urls import url, include from django.contrib import admin # from blog import views urlpatterns = [ url(r'', include('blog.urls')), url(r'^admin/', admin.site.urls), url(r'^cadmin/', include('cadmin.urls')), ]
urls.py file as follows:
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'', include('blog.urls')), url(r'^admin/', admin.site.urls), url(r'^cadmin/', include('cadmin.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now visit http://127.0.0.1:8000/media/abc.jpg, this time you should be able to see the image.
Just as with static files, method employed here to serve media files is not recommended in production environment. Infact, we will use nginx server to serve both media and static files. We will discuss how to do this in Django Deployment chapter.