Django的身份验证表单始终无效

时间:2017-08-22 17:51:46

标签: django django-models django-forms

我尝试使用Django与使用AbstractUser类的自定义用户实现基本登录系统。 这是我的models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser

class Stock(models.Model):
    stock_name = models.CharField(max_length=10)
    stock_price = models.FloatField()

    def __str__(self):
        return self.stock_name

class CustomUser(AbstractUser):
    stocks = models.ManyToManyField(Stock)

    def __str__(self):
        return self.username

我的forms.py:

from .models import CustomUser,Stock
from django.contrib.auth.forms import AuthenticationForm

class loginform(AuthenticationForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'password')

我的views.py:

def successful_login(request, pk):
    user = get_object_or_404(CustomUser, pk=pk)
    return render(request, '../templates/stock_portfolio.html', {'user':user})

def loginview(request):
    err=0
    if request.method=="POST":
        form = loginform(request.POST)
        pdb.set_trace()
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                pdb.set_trace()
                login(request, user)
                pk = user.id
                pdb.set_trace()
                return redirect('successful_login', pk=pk)
        else:
            err=1
            return render(request,'../templates/login.html',{'response':err,'form':form})
    else:
        form = loginform()
    return render(request, '../templates/login.html',{'form':form})

在这里使用pdb进行日志记录是我为表单获取的内容。

<loginform bound=False, valid=Unknown, fields=(username;password)>

我现在该怎么办?

1 个答案:

答案 0 :(得分:3)

回答这个问题,因为我刚刚遇到了同样的问题并找到了问题。更改

form = loginform(request.POST)

form = loginform(data=request.POST)

对我来说就像是一种魅力。