Categories
Python Answers

How to set file upload size limit with Python Django?

Spread the love

To set file upload size limit with Python Django, we can create our own function to do the check.

For instance, we write

from django.core.exceptions import ValidationError

def file_size(value): 
    limit = 2 * 1024 * 1024
    if value.size > limit:
        raise ValidationError('File too large. Size should not exceed 2 MiB.')

to create the file_size function to check if the size of the file is bigger than the limit where both are in bytes.

We raise a ValidationError if the size exceeds the limit.

Then in our model, we add that as the validator by writing

image = forms.FileField(required=False, validators=[file_size])

to create a file field with validators set to [file_size] to add file_size as the validator function for the file field.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *