How can I restrict FileField
to only accept a certain type of file (video, audio, pdf, etc.) in an elegant way, server-side?
One very easy way is to use a custom validator.
In your app's validators.py
:
def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls'] if not ext.lower() in valid_extensions: raise ValidationError('Unsupported file extension.')
Then in your models.py
:
from .validators import validate_file_extension
... and use the validator for your form field:
class Document(models.Model): file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])
See also: How to limit file types on file uploads for ModelForms with FileFields?.
Warning
For securing your code execution environment from malicious media files
- Use Exif libraries to properly validate the media files.
- Separate your media files from your application code execution environment
- If possible use solutions like S3, GCS, Minio or anything similar
- When loading media files on client side, use client native methods (for example if you are loading the media files non securely in a browser, it may cause execution of "crafted" JavaScript code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With