还有其他几个类似的问题带有答案,但没有一个解决我的问题。我得到的'您有多个身份验证后端配置了多个身份验证,因此必须提供backend
参数或在用户上设置backend
属性。这是我的观点:
def signupUser(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save(commit=False)
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
form.save()
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
我添加了user.backend = 'django.contrib.auth.backends.ModelBackend'
,希望解决问题,但什么也没做。
我的forms.py:
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
password1=forms.CharField(help_text='Your password cant be too similar to your other personal information. Your password must contain at least 8 characters. Your password cant be a commonly used password. Your password cant be entirely numeric.', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
顺便说一句,在我的authentication_backends中是'django.contrib.auth.backends.modelbackend'和'allauth.account.auth.auth_backends.authenticationbackend',
您的视图函数中有一些错误。我不知道这是如何解决的,但是为了清楚起见,我想指出一些。
主要是,我将您的观点重新写入更合适的方式,
def signupUser(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save(commit=False)
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
form.save()
user = authenticate(username=username, password=raw_password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
在这里,该视图旨在创建新用户。因此,在调用authenticate()
函数之前,您可能需要调用form.save()
方法。在进行数据库之前,您正在尝试对尚未创建的用户进行身份验证。检查您的视图是否确实在任何用户中登录。然后,authenticate()
函数返回无,如果凭据中存在任何不匹配,则也要检查。否则,Django在调用login()
函数时会提出AttributeError
。
我严重怀疑您的视图会在任何用户中登录,因为无论登录的成功,您都将重定向到同一页面。它非常违反直觉,使调试变得更加困难。登录成功时,只需重定向到主页,如果不是。
我意识到,即使出现了此错误,仍在创建用户,因此我想它可以完成工作。但是要摆脱这个错误,我改变了我的看法:
def signupUser(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save(commit=False)
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
form.save()
try:
login(request, user)
except ValueError:
return redirect('home')
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
这很奇怪(至少对我来说很奇怪(锻炼了。创建了用户,可以正确登录。我认为这没有任何不良的副作用,但是在有更好的解决方案的情况下,我会等待标记我的解决方案。