Django:从视图添加non_field_error? [英] Django: Add non_field_error from view?

查看:146
本文介绍了Django:从视图添加non_field_error?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django表单与一堆字段,我正在模板中呈现。我还有一些直接的HTML输入元素,我想通过访问 request.POST vars在视图中进行验证。如果这些没有验证,我想在Django表单中注入一个错误,所以我可以在页面上显示它。有没有办法这样做?

解决方案

您还可以使用相当优雅的 add_error()方法。对于Django> = 1.7。



如果将字段设置为 form将以错误的形式处理为non_field。
so:



form.add_error(无,我是非字段错误)



像一个魅力一样。


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?

解决方案

You can also use quite elegant add_error() method. Works for Django >= 1.7.

If you set field as None form will treat with error as "non_field" one. So:

form.add_error(None, "I'm non-field error")

works like a charm.

这篇关于Django:从视图添加non_field_error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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