Please help me understand if the following choices I have made are idiomatic/good and if not, how to improve.
1) Model Validation over Form Validation
I prefer to use the new model validation over form validation whenever possible as it seems a more DRY and fundamental way to create rules for the data. Two examples for a simple calendar-entry model:
- "start must be before end"
- "period must be less than (end-start)"
Is it idiomatic/good to put those at the model level so they don't have to be put into forms? If ModelForm is the best answer, then what about the case of using multiple models in the same form?
(edit: I didn't realize that multiple ModelForms can actually be used together)
2) Transferring Model Validation to a Form (not ModelForm)
(edit: It turns out reinventing the plumbing between model validation and form validation is not necessary in my situation and the solutions below show why)
Let's assume for a moment that any model validation errors I have can be directly transferred and displayed directly to the user (i.e. ignore translating model validation errors to user-friendly form validation errors).
This is one working way I came up with to do it (all in one place, no helper functions):
view_with_a_form:
...
if form.is_valid():
instance = ...
...
#save() is overridden to do full_clean with optional exclusions
try: instance.save()
except ValidationError e:
nfe= e.message_dict[NON_FIELD_ERRORS]
#this is one big question mark:
instance._errors['__all__'] = ErrorList(nfe)
#this is the other big question mark. seems unnatural
if form.is_valid()
return response...
... #other code in standard format
#send the user the form as 1)new 2)form errors 3)model errors
return form
As commented in the code:
a) Is this an idiomatic/good way to transfer model errors to a form?
b) Is this an idiomatic/good way to test for new "form" errors?
Note: This example uses non-field errors, but I think it could equally apply to field errors.