Django:如何使用通用CreateView在注册后直接登录用户

时间:2014-10-22 14:43:47

标签: python django-authentication django-generic-views

使用django generic CreateView我可以创建一个新的用户帐户,但是如何在注册后使用这种技术自动登录该用户?

urls.py

...    
url( r'^signup/$', SignUpView.as_view(), name = 'user_signup' ),
...

views.py

class SignUpView ( CreateView ) :    
    form_class = AccountCreationForm
    template_name = 'accounts/signup.html'
    success_url = reverse_lazy( 'home' )

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

2 个答案:

答案 0 :(得分:15)

它可能晚了,但这正是我的问题,经过几个小时的挣扎终于找到了。

也许你找到了,但如果其他人正在寻找解决方案,那么这就是我的。

您只需在类继承CreateView中覆盖form_valid()。以下是我自己的类的示例:

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

我首先在form_valid()中捕获父类方法valid的值,因为当你调用它时,它调用form.save(),它在数据库中注册你的用户并填充你的{ {1}}创建了用户。

之后我的身份验证问题很长,返回self.object。这是因为我使用django哈希密码调用None,并再次对其进行身份验证。

解释这一点,以便您了解我使用authenticate()而不是form.cleaned_data.get('username')的原因。

我希望它对你或其他人有所帮助,因为我没有在网上找到明确的答案。

答案 1 :(得分:0)

在Django 2.2中,我没有按Bestasttung的要求进行工作。但是我在form_valid方法上做了一点改动。

class CreateAccountView(CreateView):
    template_name = 'auth/create_account.html'
    form_class = SignInForm
    success_url = '/'

    def form_valid(self, form):
        valid = super().form_valid(form)

        # Login the user
        login(self.request, self.object)

        return valid