Django 1.9 form.is_valid()返回false

时间:2016-02-09 15:18:48

标签: python django django-forms

我正在尝试使用django自己的USER模型验证用户名和密码。 POST请求有效,form.py?

有什么问题

views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .forms import LoginForm
from django.contrib.auth import authenticate, login as auth_login

def login(request):
    msg = "Login"
    if (request.method == "POST"):

        form = LoginForm(request.POST or None)
        msg = "post"
        if form.is_valid():
            msg = "valid"

    context = {
        "msg":msg,
    }

    return render(request, "login.html", context)

forms.py

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

class LoginForm(forms.ModelForm):
    class Meta:
        model = User
        fields = [
            "username",
            "password"
        ]

的login.html

<div class="container">
        {% if user.is_authenticated %}
            blablabla
        {% else %}
        <div class="row">
            <div class="col-md-6" style="background-color: lightblue">
                <h1 style="color:red">{{ msg }}</h1>
                <form method="POST" action="">{% csrf_token %} 
                    acronym<input type="acronym" name="acronym">
                    password<input type="password" name="password">
                <input type="submit" value="Login">
                </form>
            </div>
        {% endif %}

编辑添加了login.html文件

1 个答案:

答案 0 :(得分:0)

表单不在您的上下文中,也没有为get请求实例化。

首先尝试这样的事情;

def login(request):
    msg = "Login"
    form = LoginForm()

    if (request.method == "POST"):

        form = LoginForm(request.POST or None)
        msg = "post"
        if form.is_valid():
            msg = "valid"

    context = {
        "form": form,
        "msg":msg,
    }

    return render(request, "login.html", context)

这样您就可以检查模板中的{{ form.errors }}以查看错误。

目前如何在login.html中呈现表单?你是否在这样的形式的字段上使用循环;

<form class="form" action="" method="POST">

    {% if form.non_field_errors or form.errors %}
        <div class="error-list-block">
            <p>
                Please correct the errors below - Ensure all required fields
                are completed.
            </p>
            <ul>
                {% for error in form.non_field_errors|add:form.errors %}
                    <li>{{ error }}</li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}

    {% csrf_token %}
    {% for field in form %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}