python / intermediate
Snippet
Dynamic File Extension Validator for Custom Django Forms
In Django forms, clean_<fieldname>() methods let you define custom validation rules for individual fields. Here, we extract the file extension and raise a ValidationError if the file type isn't allowed.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django import formsfrom django.core.exceptions import ValidationErrorclass DocumentUploadForm(forms.Form):allowed_extensions = ['.pdf', '.docx']file = forms.FileField()def clean_file(self):uploaded_file = self.cleaned_data.get('file')if uploaded_file:ext = uploaded_file.name.rsplit('.', 1)[-1].lower()if f".{ext}" not in self.allowed_extensions:raise ValidationError(f"Unsupported file type '.{ext}'. Must be PDF or DOCX.")return uploaded_file
django
Breakdown
1
from django import forms
Import the Django forms module to construct form classes.
2
def clean_file(self):
Define a custom field validation method specifically targeting the 'file' field.
3
uploaded_file = self.cleaned_data.get('file')
Retrieve the cleaned file object from the form's cleaned_data dictionary.
4
ext = uploaded_file.name.rsplit('.', 1)[-1].lower()
Extract the file extension reliably using rsplit and normalize it to lowercase.
5
raise ValidationError(f"Unsupported file type '.{ext}'. Must be PDF or DOCX.")
Raise a Django ValidationError to interrupt form processing and supply user error context.