Django加注不被召唤

时间:2018-02-14 06:02:38

标签: django authentication django-forms django-views django-login

    //forms.py :

//这是我应用的表单部分。

    from django import forms
    from django.contrib.auth import (
    authenticate,
    login,
    get_user_model,
    logout,
    )

    User=get_user_model()

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

        def clean(self):
            username=self.cleaned_data.get('username')
            password=self.cleaned_data.get('password')
            user=authenticate(username=username,password=password)
            if not user:
                raise forms.ValidationError("This user does not exist")

            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password")

            if not user.is_active:
                raise forms.ValidationError("This user is no longer active")

            return super(UserLoginForm,self).clean()

   // views.py :

//查看部分在哪里,我使用了在表单中创建的UserLoginForm。

    from django.shortcuts import render
    from django.contrib.auth import (
    authenticate,
    login,
    get_user_model,
    logout,
    )
    from .forms import UserLoginForm

    def login_view(request):
        if request.method=='POST':
            form=UserLoginForm(request.POST or None)
            if form.is_valid():
                username=form.cleaned_data.get("username")
                password=form.cleaned_data.get("password")
                return render(request,"accounts/home.html")
        else:
            form=UserLoginForm()

        return render(request,"accounts/login.html",{"form":form})

    def register_view(request):
        return render(request,"form.html",{})

    def logout_view(request):
        return render(request,"form.html",{})


    //login.html :

// login.html以主页打开。

    <div>
    <form method='POST' action=''>{% csrf_token %}
    <input type="text" name="username" placeholder="Username"/>
    <input type="password" name="password" placeholder="Password"/>
    <input type="submit" value="Login"/>
    </form>
    </div>

没有错误,但是无效的//填充错误都没有出现,也没有页面重定向到有效用户的home.html。请帮我解决问题。我无法找到问题。

1 个答案:

答案 0 :(得分:1)

Rendering form error messages显示错误消息...

<form method='POST' action=''>{% csrf_token %}
    {{ form.non_field_errors }}
    <input type="text" name="username" placeholder="Username"/>