60đź‘Ť
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.
24đź‘Ť
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
- [Django]-Django annotation with nested filter
- [Django]-User Registration with error: no such table: auth_user
- [Django]-Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
6đź‘Ť
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...
- [Django]-Django: Can I create a QueryDict from a dictionary?
- [Django]-How do I import the Django DoesNotExist exception?
- [Django]-Localized date strftime in Django view