Иго*_*шко 9 python django-authentication django-generic-views
使用django generic CreateView我可以创建一个新的用户帐户,但是如何在注册后使用这种技术自动登录该用户?
urls.py
...
url( r'^signup/$', SignUpView.as_view(), name = 'user_signup' ),
...
Run Code Online (Sandbox Code Playgroud)
views.py
class SignUpView ( CreateView ) :
form_class = AccountCreationForm
template_name = 'accounts/signup.html'
success_url = reverse_lazy( 'home' )
Run Code Online (Sandbox Code Playgroud)
forms.py
class AccountCreationForm ( forms.ModelForm ) :
def __init__( self, *args, **kwargs ) :
super( AccountCreationForm, self ).__init__( *args, **kwargs )
for field in self.fields :
self.fields[field].widget.attrs['class'] = 'form-control'
password1 = forms.CharField( label = 'Password', widget = forms.PasswordInput )
password2 = forms.CharField( label = 'Password confirmation', widget = forms.PasswordInput )
class Meta :
model = User
fields = ( 'email', 'first_name', )
def clean_password2 ( self ) :
# Check that the two password entries match
password1 = self.cleaned_data.get( "password1" )
password2 = self.cleaned_data.get( "password2" )
if password1 and password2 and password1 != password2:
raise forms.ValidationError( "Passwords don't match" )
return password
def save( self, commit = True ) :
# Save the provided password in hashed format
user = super( AccountCreationForm, self ).save( commit = False )
user.set_password( self.cleaned_data[ "password1" ] )
if commit:
user.save()
return user
Run Code Online (Sandbox Code Playgroud)
Bes*_*ung 16
这可能是晚了,但这正是我的问题,经过几个小时的挣扎终于找到了答案.
也许你找到了,但如果其他人正在寻找解决方案,这就是我的.
您只需form_valid()在类中重写继承CreateView.以下是我自己的类的示例:
class CreateArtistView(CreateView):
template_name = 'register.html'
form_class = CreateArtistForm
success_url = '/'
def form_valid(self, form):
valid = super(CreateArtistView, self).form_valid(form)
username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')
new_user = authenticate(username=username, password=password)
login(self.request, new_user)
return valid
Run Code Online (Sandbox Code Playgroud)
我第一次赶上我的父类方法的价值form_valid()的valid,因为当你调用它,它会调用form.save(),其注册用户数据库并填充self.object与创建的用户.
在那之后,我的身份验证遇到了很长时间的问题None.这是因为我authenticate()使用django哈希密码调用,并再次验证哈希值.
解释这个让你理解为什么我使用form.cleaned_data.get('username')而不是self.object.username.
我希望它对你或其他人有所帮助,因为我没有在网上找到明确的答案.