Django: Add non_field_error from view?

喜你入骨 提交于 2019-12-21 03:11:08

问题


I've got a Django form with a bunch of fields 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?


回答1:


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.




回答2:


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



回答3:


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...


来源:https://stackoverflow.com/questions/4229024/django-add-non-field-error-from-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!