添加错误到Django表单错误.__ all__ [英] adding errors to Django form errors.__all__

查看:383
本文介绍了添加错误到Django表单错误.__ all__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在清理数据后,如何将错误添加到表单顶部?我有一个对象需要对外部应用程序(google maps)进行REST调用作为预保存条件,这可能会失败,这意味着我需要我的用户更正表单中的数据。所以我清理数据,然后尝试保存并添加到表单错误,如果保存不起作用:

How do I add errors to the top of a form after I cleaned the data? I have an object that needs to make a REST call to an external app (google maps) as a pre-save condition, and this can fail, which means I need my users to correct the data in the form. So I clean the data and then try to save and add to the form errors if the save doesn't work:

if request.method == "POST":
#clean form data
    try:
        profile.save()
        return HttpResponseRedirect(reverse("some_page", args=[some.args]))
    except ValueError:
        our_form.errors.__all__ = [u"error message goes here"]
return render_to_response(template_name, {"ourform": our_form,}, 
       context_instance=RequestContext(request))

无法在单元测试中返回错误文本它们在{{form.non_field_errors}}中寻找),然后当我通过调试器运行它时,错误没有被添加到表单错误dict中,当它们到达render_to_response行时,也没有在our_form树中的任何其他地方。为什么这不工作?清理后,我应该怎样在窗体顶部添加错误?

This failed to return the error text in my unit-tests (which were looking for it in {{form.non_field_errors}}), and then when I run it through the debugger, the errors had not been added to the forms error dict when they reach the render_to_response line, nor anywhere else in the our_form tree. Why didn't this work? How am I supposed to add errors to the top of a form after it's been cleaned?

推荐答案

你真的想这样做表单验证并从那里提出ValidationError,但是如果您这样做,您将需要访问 _errors 添加新消息。尝试这样的东西:

You really want to do this during form validation and raise a ValidationError from there... but if you're set on doing it this way you'll want to access _errors to add new messages. Try something like this:

from django.forms.util import ErrorList

our_form._errors["field_name"] = ErrorList([u"error message goes here"])

这篇关于添加错误到Django表单错误.__ all__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆