Django表单验证。无错误显示

时间:2018-08-09 06:45:03

标签: django django-forms

授权表单 forms.py

class LoginForm(forms.Form):
        username = forms.CharField(label='Enter your login')
        password = forms.CharField(label='Enter your password', widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError('User with such login is not registered!')


        user = User.objects.get(username=username)
        if user and not user.check_password(password):
            raise forms.ValidationError('Incorrect password!')

views.py

中的代码
def login_view(request):

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            login_user = authenticate(username=username, password=password)
            if login_user:
                login(request, login_user)
                return redirect('/')
    else:
        form = LoginForm()
    return render(request, 'registration/login_view.html', {'form': form})

login_view.html

{% extends 'base.html' %}
{% block content %}
<div class="title">Вход</div>
<section id="login" class="border">
  <form id="login-form" action="" method="POST">
    {% csrf_token %}
    {% for field in form %}
    {{ field.errors }}

    <ul>
      <li>{{ field.label }} *</li>
      <li>
        <input class="input" name="{{ field.name }}" type="{{ field.name }}" /> </li>
    </ul>
    {% endfor %}
    <div>
      <span><input class="block" type="submit" value="Войти" /></span>
    </div>
  </form>
</section>
{% endblock content %}

该表单不显示验证错误,而只是重置所有字段。我在代码中找不到问题。。。这里可能是错误的.. ??????

1 个答案:

答案 0 :(得分:0)

系统提示我解决问题 就我而言,错误与表格有关,而不与特定字段有关 每个周期需要移动{{field.errors}},并更改为{{form.non_field_errors}}

{% extends 'base.html' %}
{% block content %}
<div class="title">Вход</div>
<section id="login" class="border">
  <form id="login-form" action="" method="POST">
    {% csrf_token %}
    {{ form.non_field_errors }}
    {% for field in form %}
    <ul>
      <li>{{ field.label }} *</li>
      <li>
        <input class="input" name="{{ field.name }}" type="{{ field.name }}" /> </li>
    </ul>
    {% endfor %}
    <div>
      <span><input class="block" type="submit" value="Войти" /></span>
    </div>
  </form>
</section>
{% endblock content %}