Django check calling clean () even if the requested value is missing

I am new to Django and somewhat confused about the validation steps during form processing. I know that by default all types of form fields (in my case ModelForm) are required. I suggested that Django raise a VaidationError if the required form field is left blank without invoking a form cleanup method.

This is why I did not check if any data was installed in the following clean () method:

def clean(self): date = self.cleaned_data.get('date') time_start = self.cleaned_data.get('time_start') time_end = self.cleaned_data.get('time_end') user_type = self.cleaned_data.get('user_type') if Event.objects.filter(user_type=user_type, date=date, time_start__lt=time_start, time_end__gt=time_start).exclude(pk=self.instance.pk).count(): raise forms.ValidationError("Overlapping with another event.") 

Submitting a form while leaving all fields blank causes

ValueError: cannot use None as the value of the request.

If I remove my clean () method, I get the expected ValidationErrors so that I don’t fill out the required fields - this is what I expected when the clean () method was still in place.

Any idea what might trigger this? I would be surprised if Django does not check the required values ​​before it calls clean.

+4
source share
1 answer

This is strange because field validation is performed before the clean form method is called. In addition, an error that occurs from the field is saved in form.my_field.errors , and errors returned from the form cleaning method are accumulated in form.non_field_errors .

The following is the order of checks performed on the form:

 full_clean() | Field clean() [field built-in clean method] | Form clean_*() [custom validation method for field] | Form clean() [form clean method] | cleaned_data/errors 
+4
source

Source: https://habr.com/ru/post/1434487/


All Articles