如何在django中将错误信息附加到form.non_field_errors? [英] How to append error message to form.non_field_errors in django?
问题描述
form.errors ['__ all__'] = form.error_class([error msg ])
这将显示错误消息,但似乎也搞砸了其他页面以及dis如果我点击任何其他的错误消息。
我尝试过
form._errors [NON_FIELD_ERRORS] =表单。 error_class()
这导致NoneType对象对我没有属性setdefault错误。 / p>
我试过
form.non_field_errors()。append(请填写您的个人资料以访问该内容。)
这似乎没有做任何事情我看不到错误消息。
这样做最好的方法是什么?理想情况下,我不想在表单的干净方法中做。我觉得我应该能够在视图中的表单中附加一个错误。
-
调用full_clean()
form._errors
。 -
制作错误列表,这个步骤非常重要,如果你不这样做,获取消息列表,将其设置为:
error_list = form.error_class(['your error messages'])
将错误列表分配给NON_FIELD_ERRORS ,您必须从
django.forms.forms导入 NON_FIELD_ERRORS
,然后分配: form._errors [NON_FIELD_ERRORS] = error_list
这是一个shell的演示:
在[1]中:从下注.forms import BetForm
在[2]中:从django.forms.forms导入NON_FIELD_ERRORS
在[3]中:form = BetForm()
在[4]中:form.full_clean()
在[5]中:form._errors [NON_FIELD_ERRORS] = form.error_class(['你的错误消息'])
在[6]中:form.non_field_errors()
Out [6]:[u'your error messages']
I have a form with several fields. I have separate validation checks for each field, done via the forms validation. I however also need to check if few fields are filled in before redirecting the user to a different view. I was hoping I could somehow append the error to forms.non_field_errors as it is not for a particular field , but I am not sure what the right syntax for this would be. I have checked online and found..
form.errors['__all__'] = form.error_class(["error msg"])
This displays the error message, but it seems to mess up the other pages as well and displyas the error message if I click on anything else.
I tried
form._errors[NON_FIELD_ERRORS] = form.error_class()
This causes a 'NoneType' object has no attribute 'setdefault' error for me.
I have tried
form.non_field_errors().append("Please complete your profile in order to access the content.")
This doesn't seem to do anything and I cant see the error message on the view.
What would be the best way to do this? Ideally I dont' want to do it in the form's clean method. I feel like I should be able to append an error to the form in the view.
Call full_clean(), this should initialize
form._errors
. This step is critical, if you don't do it, it won't work.Make the error list, it takes a list of messages, instanciate it as such:
error_list = form.error_class(['your error messages'])
Assign the error list to NON_FIELD_ERRORS, you have to import
NON_FIELD_ERRORS
fromdjango.forms.forms
, then assign as such:form._errors[NON_FIELD_ERRORS] = error_list
Here is a demonstration from a shell:
In [1]: from bet.forms import BetForm
In [2]: from django.forms.forms import NON_FIELD_ERRORS
In [3]: form = BetForm()
In [4]: form.full_clean()
In [5]: form._errors[NON_FIELD_ERRORS] = form.error_class(['your error messages'])
In [6]: form.non_field_errors()
Out[6]: [u'your error messages']
这篇关于如何在django中将错误信息附加到form.non_field_errors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!