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:
-
file_sizefunction: 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 aValidationErrorindicating that the file size is larger than 2 MiB. -
validate_file_extensionfunction: This function is another validator used to check the file extension of the uploaded file. It extracts the file extension from the filename usingos.path.splitext(value.name)[1], wherevalueis 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 aValidationErrorindicating that the file type is unsupported. -
DocumentFileFormclass: This is a Django form class that inherits fromBootstrapFormandforms.ModelForm. It includes a single fielddoc, which is aFileFieldused for file uploads. Thedocfield has two validators assigned to it:file_sizeandvalidate_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(value.name)[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',)