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.
  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 settings.py file.

Media Files Configurations

Media files depend 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 (TGDB/django_project), the same place where manage.py is located.

Open settings.py file and add the following code to the end of the file, just below STATICFILES_DIRS which we had set earlier.



This setting works similar to STATIC_URL and is used to access media files. Just below the MEDIA_ROOT setting add the following code to the end of settings.py file.


Download this image and save it as python.png in the media directory. To access the file visit You will get an HTTP 404 error like this:

But why?

The problem is that Django development server doesn’t serve media files by default. To make Django development server serve static we have to add a URL pattern in sitewide urls.py file.

First open 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:


Modify the urls.py file as follows:


Now visit again, this time you should be able to see the image.

Just as with static files, the method employed here to serve media files is not recommended in the production environment. In fact, we will use Nginx server to serve both media and static files. We will discuss how to do this in Django Deployment lesson.

Note: To checkout this version of the repository type git checkout 25a.

15 thoughts on “Handling Media Files in Django

  1. thanks for the tutorial, I have to scratch my head for the whole day because I put command below into “myproject/myapp/url.py” rather than “myproject/url.py”. Silly mistake + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

  2. I was doing it the wrong way.
    static(settings.MEDIA_ROOT, document_root=settings.MEDIA_URL)
    intead of
    static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    Thanks for the tutorial.

  3. i have the same problem
    this in urls.py


    this in settings.py


  4. Thank you, I spend a lot of time on how to serve media file in Django, but in vain, not found a clear concept.
    After reading this tutorial, I am now able to serve media file, really thankful to you.

Leave a Comment

%d bloggers like this: