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.