【发布时间】: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>
{{ 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