Django: How to login user directly after registration using generic CreateView

◇◆丶佛笑我妖孽 提交于 2019-11-28 21:43:15

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!