Django file validation
<p>The code provided seems to be a part of a Django form that handles file uploads for a model named <code>Document</code>. Let's break down the components of this code:</p> <ol> …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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',)
|