Handling user file uploads securely is a critical requirement for social networks, e-commerce stores, and learning management systems. Django provides robust abstractions through FileField and ImageField to validate, store, and serve user media.
# mywebsite/settings.py
# URL that handles the media served from MEDIA_ROOT
MEDIA_URL = '/media/'
# Absolute filesystem path to the directory that holds user-uploaded files
MEDIA_ROOT = BASE_DIR / 'media'
Organize uploaded files into structured subfolders by date or user ID using a callable upload_to function:
# blog/models.py
from django.db import models
from django.core.validators import FileExtensionValidator
def user_avatar_path(instance, filename):
# Files uploaded to media/avatars/user_/
return f"avatars/user_{instance.user.id}/{filename}"
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
avatar = models.ImageField(
upload_to=user_avatar_path,
blank=True,
null=True,
validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png', 'webp'])]
)
resume = models.FileField(
upload_to='resumes/%Y/%m/',
blank=True,
validators=[FileExtensionValidator(allowed_extensions=['pdf'])]
)
<!-- templates/profile_edit.html -->
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Save Profile</button>
</form>
And in your view, make sure to pass request.FILES:
def edit_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
if form.is_valid():
form.save()
return redirect('profile')
Never allow users to upload executable files (.exe, .sh, .py, .php, .html). Always enforce explicit extension validators via FileExtensionValidator and limit maximum file upload size using DATA_UPLOAD_MAX_MEMORY_SIZE.
Broaden your backend architecture, REST API design, and production engineering expertise:
Review the fundamental differences between STATIC_URL and MEDIA_URL.
Build secure file upload forms with enctype='multipart/form-data'.
Validate MIME types and sanitize filenames to prevent malicious file uploads.
Offload asynchronous image resizing and PDF generation to background workers.