Reputation: 501
im using the form.add_error option of django to add customized errors to
form checks.
when i use the add_error in the ModelForm the errors are shown in the
template, but when i use it in the view it doesn't..
what might be the problem?
the modelform add_error (in the clean method):
self.add_error('field', "fdgdsfgfds.")
the view add_error:
def form_valid(self, form):
form.add_error('field', "sfsfdsfsd.")
return self.form_invalid(form)
in the template:
{{ form.errors }}
{{ field.errors }}
{{ form.non_field_errors }}
{{ form.as_table }}
Upvotes: 0
Views: 1029
Reputation: 43300
Django model forms have a certain way of working and this in essence is a good thing because it makes sure your code stays clean and that each one of your methods have a standardized flow control.
The forms clean
and clean_fieldname
methods should be where all of your validation is done, these methods get called from the forms is_valid
method and all contribute with their errors towards statings whether the form is valid or not. See my other answer for a more detailed explanation as to how is_valid
actually calls the clean methods
The form_valid
and form_invalid
are for you to handle in your view to handle what response should be shown. The django generic views by default will render success_url
if the form is valid although you may find you want to override these methods to return a JsonResponse
or similar to make your form more ajaxxy.
So any time you want to report errors, you need to use your clean methods. You may find in the future that you want to reuse a form and you don't want to repeat yourself in views by having to do validation again, so keeping all the validation contained in the form makes this possible. The views job is to handle where you want to display your form and what other context it would need.
Upvotes: 2