我有两个表单login.html和register.html,我使用相同的方法在模板中显示错误,但不起作用。
的login.html
<form method="post" action="" class="ui large form">
{% csrf_token %}
<div class="ui stacked segment">
{% if not form.non_field_errors %}
<div class="required field">
<label>Emailaddress</label>
{{ form.username }}
</div>
{% endif %}
{% if form.non_field_errors %}
<div class="required field error">
<label>Emailaddress</label>
{{ form.username }}
</div>
{% endif %}
{% if not form.non_field_errors %}
<div class="required field">
<label>Password</label>
{{ form.password }}
</div>
{% endif %}
{% if form.non_field_errors %}
<div class="required field error">
<label>Password</label>
{{ form.password }}
</div>
{% endif %}
<small><p>{{ form.non_field_errors }}</p></small>
<input type="submit" name="" class="ui fluid large teal submit button" value="login">
</div>
</form>
输出截图:
register.html
<form method="post" action="" class="ui large form">
{% csrf_token %}
<div class="ui stacked segment">
{% if not form.non_field_errors %}
<div class="required field">
<label>Emailaddress</label>
{{ form.email }}
</div>
{% endif %}
{% if form.non_field_errors %}
<div class="required field error">
<label>Emailaddress</label>
{{ form.email }}
<p>{{ form.email.errors }}</p>
</div>
{% endif %}
{% if not form.non_field_errors %}
<div class="required field">
<label>Password</label>
{{ form.password1 }}
</div>
{% endif %}
{% if form.non_field_errors %}
<div class="required field error">
<label>Password</label>
{{ form.password1 }}
<p>{{ form.password1.errors }}</p>
</div>
{% endif %}
{% if not form.non_field_errors %}
<div class="required field">
<label>Confirm Password</label>
{{ form.password2 }}
</div>
{% endif %}
{% if form.non_field_errors %}
<div class="required field error">
<label>Confirm Password</label>
{{ form.password2 }}
<p>{{ form.password2.errors }}</p>
</div>
{% endif %}
<small><p>{{ form.non_field_errors }}</p></small>
<input type="submit" name="" class="ui fluid large teal submit button" value="Sign Up">
</div>
</form>
这次我没有收到任何显示的错误消息。我做错了什么?
答案 0 :(得分:0)
non_field_errors()
,顾名思义,显示与字段无关的错误(docs)。
请注意,Form.clean()覆盖引发的任何错误都不会与任何字段相关联。它们进入一个特殊的“字段”(称为 all ),如果需要,可以通过non_field_errors()方法访问它。
您不应该将其用作特定字段是否有错误的逻辑。你应该这样做:
{% if not form.email.errors %}
<div class="required field">
<label>Emailaddress</label>
{{ form.email }}
</div>
{% endif %}
然后在您的login.html
中,您不像{{ field.errors }}
那样呈现register.html
:
{% if form.non_field_errors %}
<div class="required field error">
<label>Emailaddress</label>
{{ form.username }}
{# This is missing #}
<p>{{ form.username.errors }}</p>
</div>
{% endif %}