我知道有很多这样的问题,但没有一个问题包含明确的答案。我正在使用Django的默认身份验证,但无法显示“您的用户名/密码组合不正确”之类的内容。是否可以在不制作自定义视图功能的情况下解决此问题?
我的urls.py看起来像这样:
url(r'^login/$', auth_views.login, {'template_name': 'login.html'},
name='mysite_login')
然后我的login.html有以下代码:
{% block content %}
<section class="content">
<div class="container block">
<div class="row">
<div class="col-md-12"></div>
<form action="{% url 'mysite_login' %}" class="form-control" method="post" accept-charset="utf-8">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field|addcss:'form-control' }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text|safe }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-dark">Login</button>
<input class="form-control" type="hidden" name="next" value="{{ next }}"><br>
</form>
</div>
</div>
</div>
</section>
{% endblock %}
所以这一切都有效,除了显示错误消息。我已经看到了你可以编写自定义视图函数和表单来解决这个问题的答案,但我认为在使用内置登录功能时也应该可以吗?非常感谢。
答案 0 :(得分:2)
built-in login form不会在单个字段级别显示错误;说密码错误是一种安全风险,因为它确认了特定用户名的存在。因此,错误会在常规clean()
方法中引发,并通过{{ form.non_field_errors }}
显示在模板中。