【问题标题】:How to Display This Django Form Error?如何显示这个 Django 表单错误?
【发布时间】:2016-10-07 23:33:09
【问题描述】:

当您清理和验证相互依赖的字段时,如何在 Django 表单中显示错误?我有一个 Django 表单,我在其中显示像 see image 这样的字段错误。它要求我显示表单的错误属性:

# signup.html
<form action="{% url 'create-account' %}" method="post">{% csrf_token %}
    <div class="form-group">
        {% if create_account_form.errors %}           # <- attribute
            <p class="errornote">
            {% if form.errors.items|length == 1 %}
                Please correct the error below.
            {% else %}
               Please correct the errors below.
            {% endif %}
            </p>
        {% endif %}
    </div>
    <div class="form-group">
        {{ create_account_form.username.errors }}     # <- attribute
        {{ create_account_form.username }}
    </div>
    <div class="form-group">
        {{ create_account_form.password1.errors }}
        {{ create_account_form.password1 }}
    </div>
    <div class="form-group">
        {{ create_account_form.password2.errors }}
        {{ create_account_form.password2 }}
    </div>
    <div class="form-group">
        {{ create_account_form.user_type_cd.errors }}
        <label for="id_user_type_cd" id="user_type_cd">This account is for a</label>
        &nbsp;&nbsp;
        {{ create_account_form.user_type_cd }}
    </div>
    <div class="form-group">
        By clicking "Sign up" you agree to the <a href="{% url 'terms-of-service' %}">Terms of Service</a>.
    </div>
    <input type="submit" class="btn btn-primary" value="Sign Up">
</form>

我使用 error_messages 参数自定义表单错误消息:

# account/forms.py
class CreateAccountForm(forms.Form):
    USER_TYPE_CHOICES = (...)
    username = forms.CharField(
        error_messages = {'required': "Username is required."}
    )
    password1 = forms.CharField(
        error_messages = {'required': "Password is required."}
    )
    password2 = forms.CharField(
        error_messages = {'required': "Passwords must match."}
    )
    user_type_cd = forms.ChoiceField(
        choices = USER_TYPE_CHOICES,
        error_messages={'required': 'Account type is required'}
    )

问题在于,当我尝试从自定义清理方法显示错误消息时,错误消息无法正确呈现,因为它不在 error_messages 参数中。看到这个image

# account/forms.py
def clean(self):
    """ Check that passwords match. """
    super(forms.Form, self).clean()
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
            self._errors['password1'] = "Passwords must match."
    return self.cleaned_data

如何将我的 clean 方法中识别的错误放入 password1 字段的 error_messages 参数中,以便我的模板像其他表单字段一样正确格式化和呈现它?我尝试在 clean 方法中执行以下操作,但两种方法都不起作用,我不确定如何解决此问题。

# This doesn't work. It assumes that I've defined password1's error_messages like this:
password1 = forms.CharField(
  error_messages = {'required': "Password is required", 'mismatch': "Passwords must match."}
)
...
from django.forms import util
raise util.ValidationError(self.password1.error_messages['mismatch'])

# This doesn't work either.
raise forms.ValidationError("Passwords must match.")

谢谢!

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    在你的第一个 sn-p 中,你已经做到了。我不确定你想用剩下的代码做什么。

    作为您已经工作的代码的替代方案,您可以使用add_error 方法吗?另请参阅Cleaning and validating fields that depend on each other 下的完整讨论。

    【讨论】:

    • 非常感谢,丹尼尔。第一个 sn-p 工作正常,第二个 sn-p 显示错误,但它只是不在 error_messages 中,因此它没有得到错误格式。我根据您的回答使用了 add_error 并且效果很好!
    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2013-05-11
    • 2011-02-01
    • 2015-03-15
    • 2011-01-11
    • 2013-09-27
    相关资源
    最近更新 更多