Friday, September 29, 2017

Django: Form validation strange behaviour

I want to do file validation(size,type) on a field on inlineformset.


class ProductDocumentModelForm(ModelForm):

 
class Meta: model = ProductDocument
   fields
= ['document']

 
def clean_document(self):
   file
= self.cleaned_data['document']
   validate_file
(file, 'document')



Because I want to use the same validation in multiple application I created a separate function.


def validate_file(file, for_model, max_size=5000):
 
if for_model == 'document':
  max_size
= FILE_MAX_DOC_SIZE
 
 
if file.size > max_size:
 
raise ValidationError('Please keep file size under {}. Current file size is {}' .format(filesizeformat(FILE_MAX_DOC_SIZE), filesizeformat(file.size)))



The file size validation works as intended but introduce a strange behavior.


If this validation is in place and is passed the "This field cannot be blank." default validation is triggered even if the fields are not empty.


Without the file size validation in place there are no issue even if the fields are empty.


I don't understand what is the cause.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a470e4e3-3cb9-489e-930c-8adc6b6210c3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment