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

Media root is the directory where media files are stored

MEDIA_URL

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.

Step#1

Add following lines at the end of settings.py

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

Step#2

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

Step#3

we need to configure main urls.py 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('admin/', admin.site.urls),
    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

Step#4

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 manage.py makemigrations blog
$ python3.6 manage.py migrate

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

python3.6 manage.py 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.