V
V
Vadim kyklaed2017-06-22 15:53:29
Django
Vadim kyklaed, 2017-06-22 15:53:29

Authorization after user registration, how?

Hello, I have a question, I have a form and a view based on cbv

class UserFormView(CreateView):

    form_class=  MyUserCreationForm
    template_name='registration/reg.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(UserFormView, self).form_valid(form)

how to embed authorization correctly, it doesn’t want to work in this form:
class UserFormView(CreateView):

    form_class=  MyUserCreationForm
    template_name='registration/reg.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        username = self.request.POST['username']
        password = self.request.POST['password2']
        print(username)
        print(password)
        userauth = authenticate(self.request,username=username,password=password)
        print(userauth)
        if userauth is not None:
             if userauth.is_active:
                 login(self.request, userauth)
        return super(UserFormView, self).form_valid(form)

it turns out that I receive username and password and pass them to the method,
but the answer from the method is None , googling you might think that it simply does not find such a user because it has not yet been saved in the database. but the form_valid(form) method simply takes a redirect to the specified url. If the view is written with non-CBV logic, then authorization works fine in it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gasoid, 2017-07-07
@Gasoid

from django.contrib.auth import login

def view(request):
       ....
    user.is_active = True
    user.save()
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question