0 day streak
python / intermediate
Snippet

Django File Uploads with ImageField Validation

File uploads require multiple validation layers: magic byte detection prevents extension spoofing, size limits prevent storage abuse, and dimension checks ensure images meet requirements.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django import forms
from django.core.exceptions import ValidationError
import magic
class ProfilePictureForm(forms.Form):
picture = forms.ImageField()
def clean_picture(self):
image = self.cleaned_data['picture']
# Validate file type using magic bytes
mime_type = magic.from_buffer(image.read(1024), mime=True)
image.seek(0) # Reset file pointer after reading
allowed_types = ['image/jpeg', 'image/png', 'image/webp']
if mime_type not in allowed_types:
raise ValidationError('Unsupported file format')
# Validate file size (max 5MB)
if image.size > 5 * 1024 * 1024:
raise ValidationError('Image size cannot exceed 5MB')
# Validate dimensions
img = Image.open(image)
if img.width < 200 or img.height < 200:
raise ValidationError('Image must be at least 200x200 pixels')
return image
django
Breakdown
1
magic.from_buffer()
Detects actual MIME type by reading file magic bytes
2
image.size
File size in bytes from uploaded file object
3
Image.open(image)
PIL/Pillow validates actual image dimensions