How to automatically login a user after registration in django

前端 未结 3 894
攒了一身酷
攒了一身酷 2020-11-28 22:27

This is what I am currently using for registration:

def register(request):
    if request.method == \'POST\':
        form = UserCreationForm(request.POST)
          


        
3条回答
  •  無奈伤痛
    2020-11-28 22:44

    You can subclass Django's UserCreationForm and override it's save method to log them in when commit=True.

    forms.py

    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth import login
    
    class CustomUserCreationForm(UserCreationForm):
        """
        A ModelForm for creating a User and logging 
        them in after commiting a save of the form.
        """
    
        def __init__(self, request, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.request = request
    
        class Meta(UserCreationForm.Meta):
            pass
    
        def save(self, commit=True):
            user = super().save(commit=commit)
            if commit:
                auth_user = authenticate(
                    username=self.cleaned_data['username'], 
                    password=self.cleaned_data['password1']
                )
                login(self.request, auth_user)
    
            return user
    

    You just need to make sure you pass in a request object when you instantiate the form. You can do that by overriding the view's get_form_kwargs method.

    views.py

    def get_form_kwargs(self):
        form_kwargs = super().get_form_kwargs()
        form_kwargs['request'] = self.request
        return form_kwargs
    
    

    Or, make sure when you instantiate a form_class you do CustomUserCreationForm(data=request.POST, request=self.request).

提交回复
热议问题