Django file validation

Django -- Posted on Nov. 8, 2021

The code provided seems to be a part of a Django form that handles file uploads for a model named Document. Let's break down the components of this code:

  1. file_size function: This function is used as a validator for the file size. It checks if the file size (value.size) is larger than 2 MiB (2 * 1024 * 1024 bytes). If the file size exceeds this limit, it raises a ValidationError indicating that the file size is larger than 2 MiB.

  2. validate_file_extension function: This function is another validator used to check the file extension of the uploaded file. It extracts the file extension from the filename using os.path.splitext([1], where value is the uploaded file. The allowed file extensions are '.pdf' and '.docx'. If the file extension is not in the list of valid extensions, it raises a ValidationError indicating that the file type is unsupported.

  3. DocumentFileForm class: This is a Django form class that inherits from BootstrapForm and forms.ModelForm. It includes a single field doc, which is a FileField used for file uploads. The doc field has two validators assigned to it: file_size and validate_file_extension. These validators will be triggered when a user submits the form to ensure the uploaded file's size and type comply with the specified rules.

Overall, this code is a part of a Django form that enforces restrictions on file uploads for the Document model. It prevents files larger than 2 MiB and only allows files with the extensions '.pdf' and '.docx'. If any validation error occurs, Django will prevent the form from being saved and will display the corresponding error message to the user.


                def file_size(value): # add this to some file where you can import it from
    limit = 2 * 1024 * 1024
    if value.size > limit:
        raise ValidationError('File Size is larger than 2 MiB.')

def validate_file_extension(value):
    import os
    from django.core.exceptions import ValidationError
    ext = os.path.splitext([1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.docx']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file type')

class DocumentFileForm(BootstrapForm, forms.ModelForm):
    doc = forms.FileField(required=False, label='', help_text='', validators=[file_size, validate_file_extension])

    class Meta:
        model = Document
        fields = ('doc',)

Related Posts