如何显示这个Django表单错误?

时间:2016-06-07 21:47:27

标签: django django-forms django-templates

当您清理和验证彼此依赖的字段时,如何在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参数中,以便我的模板格式化并正确呈现,就像使用其他表单字段一样?我尝试在干净的方法中执行以下操作,但两种方法都不起作用,我不知道如何解决这个问题。

# 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.")

谢谢!

1 个答案:

答案 0 :(得分:0)

你已经完成了,在你的第一个片段中。我不确定你要对剩下的代码做什么。

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