How to automatically login a user after registration in django

前端 未结 3 890
攒了一身酷
攒了一身酷 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:33

    for class based views here was the code that worked for me (originally Django 1.7, updated for 2.1)

    from django.contrib.auth import authenticate, login
    from django.contrib.auth.forms import UserCreationForm
    from django.http import HttpResponseRedirect
    from django.views.generic import FormView
    
    class SignUp(FormView):
        template_name = 'signup.html'
        form_class = UserCreateForm
        success_url='/account'
    
        def form_valid(self, form):
            #save the new user first
            form.save()
            #get the username and password
            username = self.request.POST['username']
            password = self.request.POST['password1']
            #authenticate user then login
            user = authenticate(username=username, password=password)
            login(self.request, user)
            return HttpResponseRedirect(self.get_success_url)
    
    0 讨论(0)
  • 2020-11-28 22:42

    Using the authenticate() and login() functions:

    from django.contrib.auth import authenticate, login
    
    def register(request):
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                new_user = form.save()
                messages.info(request, "Thanks for registering. You are now logged in.")
                new_user = authenticate(username=form.cleaned_data['username'],
                                        password=form.cleaned_data['password1'],
                                        )
                login(request, new_user)
                return HttpResponseRedirect("/dashboard/")
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题