Django:验证几个字段 [英] Django: validating several fields

查看:137
本文介绍了Django:验证几个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档,验证相互依赖的字段的建议方法是在窗体的 clean()方法中。这是有道理的,但我正在处理的问题是如何通知视图导致问题的领域。

In the Django Documentation, the suggested way to validate fields that depend on each other is in the form's clean() method. It makes sense, but the problem I'm dealing with is how to notify the view what fields are causing problems.

当一个字段失败时,我可以检查如下:

When it's just one field who is failing, I can check it like this:

for field in form:
    if field.errors:
        # I know exactly in what field is the problem

但是如果错误来自 clean ()方法,我所得到的是错误消息:

But if the error comes from the clean() method, all I got is the error message:

if form.errors:
    for error in form.errors:
        # I know there's a problem, and I got an error message,
        # but I don't know what are the fields that cause it.

想想一下典型的注册表单,您必须在两次电子邮件中写入两次密码以避免错字。例如,如果两个密码字段的值不同,我想更改CSS类,但是在视图中,我没有引用导致问题的窗口小部件。我唯一的信息是窗体的 clean()方法中的ValidationError抛出的错误消息。如何知道问题是密码字段还是电子邮件字段?我想这个错误信息解析是不行的。

Think in the typical registration form, where you must write twice the email and twice the password to avoid typos. By example, I want to change the CSS class of the two password fields if they have different values, but in the view, I've got no reference to the widget causing the problem. The only information I have is the error message thrown by the ValidationError in the Form's clean() method. How do I know if the problem is with the password fields or with the email fields? And I guess that parsing that error message is not the way to go.

推荐答案

你可以添加一个这样的字段级错误:

You can add a field level error like this:

self._errors["<field_name>"] = self.error_class([msg])

如果您在中提出 ValidationError / code>,将导致非字段错误。请参阅文档页面。

If you raise a ValidationError in clean, it will result in a non field error. See the bottom snippet at the documentation page.

这篇关于Django:验证几个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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