0

I have recently started to use django-rest-framework in my projects and I have faced a problem. Here is a simple auth form I have:

<form action="{% url 'rest_framework:login' %}" method="post">
    {% csrf_token %}
    <input type="e-mail" name="username" value="" placeholder="Логин" maxlength="100" required="required">
    <input type="password" name="password" value="" placeholder="Пароль" maxlength="100" required="required">
    <button type="submit" class="lightbluebtn">Войти</button>
</form>

I can't really figure out how to validate it. I just need the error to be shown on the form. Every time I submit my form with invalid data I redirected to rest-framework login page. Also I have django-rest-framework default urls:

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

Is there any way to use it with django default forms?

Can you guys help me to fix it? I will be very grateful for the help.

4

1 回答 1

2

如果您使用会话身份验证的 api,那么您不需要 rest_framework 登录页面,该页面通常在开发环境中很有用,您只需指向该{% url 'login' %}页面(使用 django.contrib.auth.views.login view),并通过命名 yours 来覆盖该模板registration/login.html,用于输出表单错误只需使用{{ form.error }},例如:

{# file registration/login.html #}
{% if form.errors %}
<div class="alert alert-danger">
  <p>Your email and password didn't match. Please try again.</p>
</div>
{% endif %}
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
    <input type="e-mail" name="username" value="" placeholder="Логин" maxlength="100" required="required">
    <input type="password" name="password" value="" placeholder="Пароль" maxlength="100" required="required">
    <button type="submit" class="lightbluebtn">Войти</button>
</form>
于 2014-12-20T18:10:26.473 回答