django:form.is_valid总是给出错误

时间:2016-05-20 17:20:08

标签: django

我正在登录页面上工作,但我的表单总是给我错误,请在下面找到我的代码,请参阅view.py它的响应总是转到&#34的其他语句;如果是form.is_valid():&#34 ;条件。请帮忙

在这里你可以看到form.py

from django.contrib.auth.models import User
from django import forms

class LoginForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'password']

这是我的view.py

def login_view(request):
template_name = 'user/login.html'
form_class = LoginForm

if request.method == "POST":
    form = form_class(data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)
        try:
            login(request, user)
            return redirect('user:profile')
        except:
            form = form_class(None)
            return render(request, template_name, {'form': form, 'custom_error': 'Error'})
    else:
        return HttpResponse("<h1>Data is invalid</h1>")

else:
    if request.user.is_authenticated():
        return redirect('user:profile')
    else:
        form = form_class(None)
        return render(request, template_name, {'form': form,})

用户/ login.html的

{% block body %}
<div class="section">
      <div class="container">
        <div class="row">
            <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
                {% csrf_token %}
          <div class="col-md-5">
            <img src="{% static 'user/images/favicon.png' %}" class="img-responsive">
          </div>
          <div class="col-md-6">
            {% include 'user/form-template.html' %}
              <div class="col-sm-offset-2 col-sm-10" align="right">
                    <button type="submit" class="btn btn-default" autofocus>Sign In</button>
              </div>
          </div>
                </form>
        </div>
      </div>
    </div>

{% endblock %}

最后这是我的form-template.html文件

    {% for field in form %}
    <div class="col-md-8">
        <div class="col-md-4">
            <label>{{ field.label_tag }} </label>
        </div>
        <div class="col-md-4">
            {{ field }}
            <div>
                <span>{{ field.errors }}</span>
            </div>
            <div>
                <span class="text-danger small">{{ custom_error }}</span>
            </div>
        </div>
    </div>


{% endfor %}

2 个答案:

答案 0 :(得分:1)

如果您使用id | id_month | months | date_start | date_end 1 | 1 | 6 | 2016-01-01 | 2016-07-01 2 | 1 | 6 | 2016-03-01 | 2016-09-01 3 | 1 | 6 | 2016-06-01 | 2016-12-01 4 | 1 | 6 | 2016-08-01 | 2017-02-01 ,您将使用django模型对象,创建,更新等。如果您只是尝试登录,请改用ModelForm

答案 1 :(得分:1)

感谢它的解决,我只是改变了我的表格,看起来不像这样。

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

现在我没有使用内置表单,我也将ModelForm更改为Form。