Django: Add non_field_error from view?
I've got a Django form with a bunch of fields开发者_如何学JAVA that I'm rendering in the template. I've also got some straight HTML input elements which I want to validate in the view by accessing the request.POST
vars. If those don't validate, I want to inject an error into the Django form so I can display it on the page. Is there a way to do that?
You can also use quite elegant add_error() method. Works for Django >= 1.7.
If you set field
as None
form will treat the error as "non_field" one.
So:
form.add_error(None, "I'm non-field error")
works like a charm.
Adding to Daniel's answer, the specific syntax is:
form.errors['__all__'] = form.error_class(["error msg"])
Note that you can substitute '__all__'
with the constant NON_FIELD_ERRORS
for better compatibility (credit grafa).
from django.forms.forms import NON_FIELD_ERRORS
Well, you can insert anything into the form's errors
dictionary, and non-field errors go in errors['__all__']
.
But why are you keeping some fields out of the Django form, only to put their errors back in at the end? Why not put all the fields in the form in the first place? If it's just that you're using a modelform and you want to add fields to it, you can do this in Django by simply declaring the fields at the form level - then you can define clean methods for them within the form.
class ExtendedModelForm(forms.ModelForm):
extra_field_1 = forms.CharField()
extra_field_2 = forms.CharField()
def clean_extra_field_1(self):
...etc...
精彩评论