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.
Media files are managed using Django settings, models, forms, and URL configurations. Image uploads rely on ImageField and proper server configuration.
# Django media configuration
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Model with ImageField
from django.db import models
class Profile(models.Model):
profile_picture = models.ImageField(upload_to='profile_pics/')
# ModelForm for image upload
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['profile_picture']
# 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)
# Nginx media file configuration
server {
location /media/ {
alias /path/to/project/media/;
}
}
Uploaded images are stored inside the MEDIA_ROOT directory and accessed via MEDIA_URL. In production, the web server handles file delivery directly.
Think of MEDIA_ROOT as the warehouse and MEDIA_URL as the delivery address. Use the simulator below to understand the flow.