← Back to Chapters

Uploading and Serving Media Files

?️ Uploading and Serving Media Files

? Quick Overview

Django applications frequently need to handle user-uploaded files such as images, videos, and documents. Django provides built-in tools to upload, store, and serve media files efficiently in both development and production environments.

? Key Concepts

  • Media files are user-uploaded and dynamic
  • MEDIA_URL defines the access path
  • MEDIA_ROOT defines the storage location
  • Development and production handling differ

? Syntax & Theory

Media files are managed using Django settings, models, forms, and URL configurations. Image uploads rely on ImageField and proper server configuration.

? Code Examples

? View Code Example
# Django media configuration
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
? View Code Example
# Model with ImageField
from django.db import models

class Profile(models.Model):
    profile_picture = models.ImageField(upload_to='profile_pics/')
? View Code Example
# ModelForm for image upload
from django import forms
from .models import Profile

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['profile_picture']
? View Code Example
# Serve media files during development
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
? View Code Example
# Nginx media file configuration
server {
    location /media/ {
        alias /path/to/project/media/;
    }
}

? Output & Explanation

Uploaded images are stored inside the MEDIA_ROOT directory and accessed via MEDIA_URL. In production, the web server handles file delivery directly.

? Interactive Concept

Think of MEDIA_ROOT as the warehouse and MEDIA_URL as the delivery address. Use the simulator below to understand the flow.

? MEDIA_ROOT (Server Disk)

 
➡️

? MEDIA_URL (Browser Access)

Waiting...

? Use Cases

  • User profile pictures
  • Uploaded documents
  • Gallery images
  • Video uploads

✅ Tips & Best Practices

  • Always validate uploaded files
  • Use ImageField for image-specific uploads
  • Never serve media using Django in production

? Try It Yourself

  • Create a profile image upload feature
  • Verify files appear inside MEDIA_ROOT
  • Configure Nginx to serve uploaded images