Django 内置的 AuthenticationForm 不验证用户

问题描述 投票:0回答:3

我正在尝试使用 Django 框架构建一个登录系统。我扩展了 UserCreationForm 以添加姓名和电子邮件。现在我在数据库中有用户,我正在尝试对他们进行身份验证并登录。但是,当我调用内置的 AuthenticationForm 类,使用发布数据创建一个实例,并尝试对用户进行身份验证时,我没有得到任何结果用户返回并且身份验证失败。 view.py 文件的所有代码如下。我尝试阅读 AuthenticationForm 源代码,但没有任何帮助。有什么建议吗?

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.db import models
from django import forms
from django.forms import EmailField
from django.forms import CharField
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    email = EmailField(label=_("Email address"), required=True, help_text=_("Required."))

    class Meta:
        model = User
        fields = ('email', 'username', 'first_name', 'last_name',)

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.firstName = self.cleaned_data["first_name"]
        user.lastName = self.cleaned_data["last_name"]
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()
            return user




def signup(request):
    if request.method == 'POST': # if sending data to the server
        form = SignUpForm(request.POST)# creates form from request data
        if form.is_valid():
            user = form.save() # at this point, need to set user permissions, attach to user themselves? Add permissions this way?
            #            user.groups.set('tutors')
            user.save()

#            print(user.get_all_permissions()) # gets all permissions of user
#            print(user.groups.values_list('name',flat=True))
            # set permissions here
            # once set permissions, can close off the rest of the site and continue
            return redirect('/user/signup')
        else: # if form isn't valid
            errorMessage = True # sets flag to display error in HTML page
            form = SignUpForm()
            dict = {'errorMessage': errorMessage, 'form': form}
            return render(request, 'user/signup.html', dict) #
# pass in
    else: # if get request, return new form
        form = SignUpForm()
        return render(request, 'user/signup.html', {'form': form}) # return rendered form




#
#
#
def log_in(request):
    if request.method == 'POST':
        # need to get user from log in form

        form = AuthenticationForm(request.POST) # form isn't valid because user name isn't being passed in?
        print(form)
        user = form.get_user()
        print(user)
        # authentication form expects user name and password, needs to accept email
        if form.is_valid(): # WHY ISN'T THIS VALID
            # where to get user?
            user = form.get_user
            print("Groups: ")
            print(user.groups)

            return render(request, 'user/log_in.html', {'form': form}) #

        else:
            print("Not valid")
            return render(request, 'user/log_in.html', {'form': form}) #

````
django forms authentication forms-authentication
3个回答
4
投票

供将来参考: 需要将

AuthenticationForm
与此参数一起使用:

form = AuthenticationForm(data=request.POST)

这将使其正确验证。


0
投票

我认为问题太老了,但仍然如此。

身份验证表单

(/site-packages/django/contrib/auth/forms.py)
是 forms.Form
(/site-packages/django/forms/forms.py)
的子类。

检查表格。表格类

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
             initial=None, error_class=ErrorList, label_suffix=None,
             empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
    self.is_bound = data is not None or files is not None

除非

is_bound
未设置为 True,否则
is_valid
将返回 False。


0
投票

你可以尝试这个。请告诉我:

def log_in(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request,data=request.POST)
        if form.is_valid():
            user_name = form.cleaned_data['username']
            user_pass = form.cleaned_data['password']
            user = authenticate(username=user_name ,password = user_pass)
            if user is not None:
                login(request,user)
                return redirect('home')
    else:
        form = AuthecticationForm()
    return render(request, 'user/log_in.html', {'form': form})
© www.soinside.com 2019 - 2024. All rights reserved.