Home > Back-end >  Django: How to log user in right after they had registered with somewhat default UserCreationForm?
Django: How to log user in right after they had registered with somewhat default UserCreationForm?

Time:12-16

I'm trying to log the user in right after they had registered with the app, so that they don't have to manually log in right after. I have created RegisterForm from django's UserCreationForm and it works as it should - it creates an User object if the form is valid, but I don't know how to access that created User object to log it it using the login function, which requires, aside from request, also an user object. Note: I have edited the default User in models.py. This is my code:

class RegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args,**kwargs)
        self.fields['username'].widget.attrs.update({'class':'form-control','id':'username', 'aria-describedby':'usernameHelp'})
        self.fields['password1'].widget.attrs.update({'class':'form-control','id':'password1', 'aria-describedby':'password1Help'})
        self.fields['password2'].widget.attrs.update({'class':'form-control','id':'password2','aria-describedby':'password2Help'})
    
    class Meta:
        model = User
        fields = ['username', 'password1', 'password2', 'email', 'first_name', 'last_name',
         'photo', 'amazon', 'twitter', 'facebook', 'instagram', 'youtube']
        widgets = {
            'email':EmailInput(attrs={'class':'form-control', 'id':'email', 'aria-describedby':'emailHelp'}),
            'first_name':TextInput(attrs={'class':'form-control', 'id':'first_name',}),
            'last_name':TextInput(attrs={'class':'form-control','id':'last_name', 'aria-describedby':'nameHelp'}),
            'photo':ClearableFileInput(attrs={'class':'form-control','id':'photo', 'aria-describedby':'photoHelp'}),
            'amazon':URLInput(attrs={'class':'form-control', 'id':'amazon', 'aria-describedby':'amazonHelp'}),
            'twitter':URLInput(attrs={'class':'form-control', 'id':'twitter', 'aria-describedby':'twitterHelp'}),
            'facebook':URLInput(attrs={'class':'form-control', 'id':'facebook', 'aria-describedby':'facebookHelp'}),
            'instagram':URLInput(attrs={'class':'form-control', 'id':'instagram', 'aria-describedby':'instagramHelp'}),
            'youtube':URLInput(attrs={'class':'form-control', 'id':'youtube', 'aria-describedby':'youtubeHelp'})
        }

And here is the view:

def register(request):
    # POST
    if request.method == "POST":
        # In addition to our form we must make sure to get the files too, if photo is uploaded
        form = RegisterForm(request.POST, request.FILES or None)
        if form.is_valid():
            form.save()
            #user = User.objects.get() ???
            #login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return render(request, "astator/register.html", 
            {"form":form, 
            "message":"Something went wrong. Please try filling out the fields again. Make sure that your passwords match and that they satisfy the requirements listed bellow."
            })

    # GET
    else:
        form = RegisterForm()
        return render(request, "astator/register.html", {"form":form})

CodePudding user response:

In your form you can access your user object so you can do something like that :

if form.is_valid():
        user = form.save()
        login(request, user)
        return HttpResponseRedirect(reverse('index'))

This is explain in the documentation regarding the save method : Django Save Method

CodePudding user response:

Similar to model forms in general, the UserCreationForm returns the user model instance when you save the form.

    if form.is_valid():
        user = form.save()
        login(request, user)
        return HttpResponseRedirect(reverse('index'))

CodePudding user response:

you can create a html page then call this classView from that url and you can use django Authentication for more convenience

class LoginForm(AuthenticationForm):
    username = UsernameField(widget=forms.TextInput(
        attrs={'autofocus': True, 'class': 'form-control'}))
    password = forms.CharField(label=_("Password"), strip=False, widget=forms.PasswordInput(
        attrs={'autocomplete': 'current-password', 'class': 'form-control'}))
  • Related