Django: How to login user directly after registration using generic CreateView
it's maybe late but that was exactly my question, and after some hours of struggling finally find out.
Maybe you found but if other people are looking for a solution, here is mine.
You just have to override form_valid()
in your class Inheriting CreateView. Here is the example with my own class :
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
I first catch the value of my parent class method form_valid()
in valid
, because when you call it, it calls the form.save(), which register your user in database and populate your self.object
with the user created.
After that I had a long problem with my authenticate, returning None
. It's because I was calling authenticate()
with the django hashed password, and authenticate hash it again.
Explaining this for you to understand why I use form.cleaned_data.get('username')
and not self.object.username
.
I hope it helps you or other, since I didn't find a clear answer on the net.
In Django 2.2 I didn't managed to have it working as Bestasttung posted. But I managed with a small change in the form_valid method.
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