How to handle file upload of a certain type and size? (Looking for Best Practices / Convention)
I have the following column definition in my Django model
media = models.FileField()
I want to ensure that only video files (preferably in MP4 format) can be uploaded. Additionally, is it possible to set a maximum file size, like 200 MB? Would this approach create extra load on the server, since it would need to validate the MIME type and check that the file size doesn’t exceed the limit? I know client-side checks aren’t secure on their own since they can be bypassed, but does the csrf_token help address this on the backend?
Validating the MIME type and file size on the server side does add some load, but it is necessary for security. The server needs to ensure that the uploaded files meet the specified criteria.
The csrf_token helps protect against Cross-Site Request Forgery (CSRF) attacks, but it does not validate the file type or size. It ensures that the request is coming from a trusted source, but you still need to perform server-side validation for file uploads.
You can use django custom validator as the following:
validators.py
import os
from django.core.exceptions import ValidationError
def validate_video_file(file):
valid_mime_types = ['video/mp4']
valid_extensions = ['.mp4']
max_file_size = 200 * 1024 * 1024 # 200 MB
# Check MIME type
if file.content_type not in valid_mime_types:
raise ValidationError('Unsupported file type.')
# Check file extension
ext = os.path.splitext(file.name)[1]
if ext.lower() not in valid_extensions:
raise ValidationError('Unsupported file extension.')
# Check file size
if file.size > max_file_size:
raise ValidationError('File size exceeds the limit of 200 MB.')
Apply the validator to your model field: models.py
from django.db import models
from .validators import validate_video_file
class YourModel(models.Model):
media = models.FileField(upload_to='videos/', validators=[validate_video_file])
This implementation gives you the ability to validate the MIME type in addition to the extension of the file also the size.