这是我注册后自动登录的代码。
def authenticationRegister(request):
if request.method == 'POST':
registrationForm = MyRegistrationForm(request.POST)
if registrationForm.is_valid():
user_present = registrationForm.save()
request.session['RegistrationForm_error'] = None
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
request.session['username'] = user.email
request.session['id'] = user.id
return HttpResponseRedirect('/home/')
else:
request.session['RegistrationForm_error'] = registrationForm.errors
return HttpResponseRedirect('/authenticate/')
return HttpResponseRedirect('/authenticate/')
此代码的问题是auth.authenticate()返回None。 当我将user.login()语句放在外面时,如果出现匿名用户错误。 表单将保存在db中。但是auth.authenticate()返回None。
MyRegistrationForm的代码
class MyRegistrationForm(UserCreationForm):
error_messages = {
'duplicate_email': _("A user with that email already exists."),
'password_mismatch' : _("The two password fields didn't match."),
}
username = forms.CharField(
widget = forms.TextInput(attrs={'placeholder':'Enter Username','class': 'form-control input', 'size': '20'}),
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."))
email = forms.EmailField(
widget = forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-control input', 'size': '20'}))
password1 = forms.CharField(
widget = forms.PasswordInput(attrs={'placeholder': 'Password','class': 'form-control input', 'size': '20'}))
password2= forms.CharField(
widget = forms.PasswordInput(attrs={'placeholder': 'Confirm Password','class': 'form-control input', 'size': '20'}),
help_text = _("Enter the same password as above, for verification."))
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password1', 'password2')
def clean_email(self):
email = self.cleaned_data["email"]
try:
get_user_model()._default_manager.get(email=email)
except get_user_model().DoesNotExist:
return email
raise forms.ValidationError(
self.error_messages['duplicate_email'],
code = 'duplicate_email',)
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(self.error_messages['password_mismatch'], code = 'password_mismatch', )
return password2
答案 0 :(得分:1)
您的POST数据中没有密钥password
,因为您的密码字段为password1
和password2
。所以你的dict get
只是返回默认值,即空字符串。
正如Alasdair在评论中所说,无论如何你都应该使用clean_data表格。而且,如果表单有效,您只能达到这一点,您知道值存在,因此您不应该使用get
默认值:只使用标准的dict访问。
username = form.cleaned_data['username']
password = form.cleaned_data['password1']