Reputation: 9636
Django says "Note that if the form hasn’t been validated, calling save() will do so by checking form.errors. A ValueError will be raised if the data in the form doesn’t validate – i.e., if form.errors evaluates to True."
What I am not able to clear out is
Will the validation be run when I call the save on the ModelForm?
And if I have validated the form data using form.is_valid() method than will the save() method do the validation again.(I am asking this as some validation requires I do a database query for Foreign Key validation as it has some restriction)
I am asking this question as if the first one is true than I think it would be a good idea to not to validation at all and rather just call the save method, letting it call the validation method and just catching it.
Upvotes: 1
Views: 411
Reputation: 37319
First question - yes. As the docs say, calling save() accesses form.errors, which triggers validation if the form has not yet been validated.
Second question - no, the validation will not be run again. Once the form has been validated, whether by calling is_valid() or by calling .save(), form.errors is populated and can be read from without re-running validation.
With either approach, validation will be run exactly once.
Upvotes: 1