0
當您清理和驗證彼此相關的字段時,如何在Django表單中顯示錯誤?我有一個Django窗體,其中顯示像這樣的see image這樣的字段錯誤。它要求我顯示窗體的錯誤屬性:如何顯示此Django窗體錯誤?
# 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'}
)
的問題是,當我嘗試從自定義顯示錯誤信息clean方法,錯誤信息不能正確呈現,因爲它不在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
,我怎麼把我的乾淨的方法鑑定錯誤進入密碼1場的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.")
謝謝!
非常感謝Daniel。第一個代碼片段正常工作,第二個代碼片段顯示錯誤,但它不在error_messages中,因此它沒有得到錯誤格式。我用你的答案使用了add_error,它完美地工作! – William