模板中不显示错误

error is not displayed in the template

我已经使用 django allauth 进行用户注册和登录。我在模板中使用 {{ form.has_errors }} 来显示错误,但错误未显示在模板中。没有在模板中显示错误的原因可能是什么?

来自 allauth 的代码 login.html(account/login.html)

{% block content %}
<div class="login-box">
      <div class="row">
       <div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3 login-area">
       <span class="error">
          {% if form.has_errors %}
          <p>Your username and password didn't match. Please try again.</p>
          {% endif %}
      </span>
       <div class="panel panel-default">
         <div class="panel-heading login-header">{% trans "Sign In" %}</div>
         <div class="panel-body">
            <form class="login" method="POST" action="{% url 'account_login' %}">
              {% csrf_token %}
              <div class="form-group form-group-lg">
                <label for="emailAddress">Email address</label>
                <input type="email" class="form-control" id="emailAddress id_login" name="login" placeholder="Email">
              </div>
               <div class="form-group form-group-lg">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password id_password" name="password" placeholder="Password">
              </div>
              <div class="form-group">
                {% if redirect_field_value %}
                <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
                {% endif %}
              </div>
              <button class="btn-block signin-btn btn-sm btn-primary pull-right m-t-n-xs" type="submit">{% trans "Sign In" %}</button>
            </form>
             </div>
             <div class="panel-footer">
                <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a>
             </div>
         </div>
      </div>
    </div>
</div>
{% endblock %}

好像是对has_error的误解

his method returns a boolean designating whether a field has an error with a specific error code. If code is None, it will return True if the field contains any errors at all.

再加上您正在手动呈现表单。通常有两种类型的表单错误,非字段错误和与每个字段相关的错误(当它们的验证失败时)。上述方法接受字段名称作为参数,如果字段验证失败,则 returns 为真。

您有多种选择,包括继续您当前的方法但检查 form.errors 而不是 form.has_error 或分别显示每个字段的错误。

试试这个。未附加到字段的表单引发的错误存储在 non_field_errors

 {% if form.non_field_errors %}
          <ul class='form-errors'>
              {% for error in form.non_field_errors %}
                  <li>{{ error }}</li>
              {% endfor %}
          </ul>
  {% endif %}

或者如果你想以自己的方式展示,试试这个

{% if form.errors %}
          <p>Your username and password didn't match. Please try again.</p>
{% endif %}