How to handle media files in django application

Unlike static files, media files are the files (images , pdf or any other documents etc) uploaded by user.

For managing media files, you need to setup MEDIA_ROOT and MEDIA_URL .


Media root is the directory where media files are stored


URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value.


Add following lines at the end of

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'


Create a folder called as media at the base directory. Directory structure looks like as below
├── static
│   ├── css
│   ├── img
│   └── js
├── templates
│   ├── components
│   └── blog
├── media


we need to configure main file as below

from django.contrib import admin
from django.urls import path, include

from . import settings                                              #add this for media
from django.contrib.staticfiles.urls import static                  #add this for media
from django.contrib.staticfiles.urls import staticfiles_urlpatterns #add this for media

urlpatterns = [
    path('blog/', include('blog.urls')),# Add this line for new app

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  #add this for media


You also need to define a field which will accept media file.

class Post(models.Model):

    featured_image = models.ImageField(upload_to='img', blank=True, null=True)


Please note the “upload_to” option. Here, “img” folder will get created (you dont have to create it manually) and files will be stored and served from here.

Once these changes are done , don’t forget to run following commands

$ python3.6 makemigrations blog
$ python3.6 migrate

Now start the server using following command and start using media files.

python3.6 runserver

If you run into any issue, please let me know

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.