7- Configuring MEDIA-URL for File Uploads

In the next article, we will be working with FileUploads. Therefore, it is time to configure our MEDIA URL settings. MEDIA_URL is the URL that makes the static media accessible over HTTP. We need to configure this to tell Django where to find the uploaded files. 

Add MEDIA_URL = '/media/' in your settings.py

settings.py

MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

 

If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES.

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [(os.path.join(BASE_DIR, 'templates')),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
        },
    },
]

 

Open up your main urls.py (Project urls) and modify it like this

Import settings and static and  add 

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 
urls.py (Project's urls.py)
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('moviesapp/', include('moviesapp.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

 

Now Django knows from where to get the files we have uploaded when we use {{ MEDIA_URL }} in our template.