我正在尝试使用Django框架构建登录系统。我扩展了UserCreationForm以添加名称和电子邮件。现在我已经在数据库中有用户,我正在尝试对他们进行身份验证并登录。但是,当我调用内置的AuthenticationForm类时,使用发布数据创建实例,然后尝试对用户进行身份验证,我没有用户返回并且认证失败。下面是views.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}) #
````
答案 0 :(得分:0)
对于将来的参考: 需要将此参数与AuthenticationForm一起使用: 表格= AuthenticationForm(data = request.POST)
这将使其正确验证。
答案 1 :(得分:0)
我认为问题太老了,但仍然如此。
身份验证表单 (/site-packages/django/contrib/auth/forms.py)
是表单的子类。表单 (/site-packages/django/forms/forms.py)
。
检查 forms.Form 类
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。