Skip to content
thesarfo

Note

File Validation

Writing a custom validator to cap uploaded file size, and validating file extensions with FileExtensionValidator.

views 0

Now lets say while allowing users to upload images, we want to set a limit to the size of the image that can be uploaded. We can validate that in django. First, create a validators.py file in the desired app, and define your validation logic in there. see below

from django.core.exceptions import ValidationError
def validate_file_size(file):
max_size_kb = 50
if file.size > max_size_kb * 1024:
raise ValidationError(f'Files cannot be larger than {max_size_kb}KB')

Now inside your models.py you have to apply this validation to the preferred field(image). Now in our product image model this is what we do. see below

from .validators import validate_file_size
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
image = models.ImageField(upload_to='store/images', validators=[validate_file_size])

We have added an array of validators to our image field, and here we validate the file size.

If we had a FileField instead of an image field, we could similarly validate the extensions of the files that are being uploaded. see below

from django.core.validators import FileExtensionValidator
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
image = models.FileField(upload_to='store/images', validators=FileExtensionValidator(allowed_extensions[pdf]))

Now when a file without the pdf extension is uploaded, django will raise a validation error.