← Back to Chapters

Configuring MEDIA_URL & MEDIA_ROOT

?️ Configuring MEDIA_URL & MEDIA_ROOT

? Quick Overview

Django uses MEDIA_URL and MEDIA_ROOT to manage user-uploaded files like images, videos, and documents. These settings define where files are stored and how they are accessed.

? Key Concepts

  • Media files are dynamic and user-uploaded
  • They differ from static files (CSS, JS)
  • Django separates storage path and access URL

? Syntax / Theory

MEDIA_URL defines the public URL, while MEDIA_ROOT defines the server directory where files are saved.

? View Code Example
# URL prefix used to access media files
MEDIA_URL = '/media/'
? View Code Example
# Directory where uploaded files are stored
import os
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

? Using Media Files in Templates

? View Code Example
# Display uploaded image and document
Photo
Download

? Serving Media in Development

? View Code Example
# Enable media serving in development
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

? Serving Media in Production

? View Code Example
# Nginx configuration for media files
location /media/ {
    alias /path/to/project/media/;
}

?️ Interactive: Path Simulator

Modify the values below to see the difference between where Django saves a file versus how it serves it.

? MEDIA_ROOT (File System Storage):
? Browser URL (Public Access):
? Template Usage:

? Use Cases

  • User profile pictures
  • Product images
  • Document uploads

✅ Tips & Best Practices

  • Always separate static and media files
  • Use Nginx or Apache in production
  • Ensure write permissions on MEDIA_ROOT

? Try It Yourself

  • Upload an image using a Django form
  • Display it using MEDIA_URL
  • Configure Nginx to serve media