简体   繁体   中英

how to login automatically after signup in django class base view

i want to login automatically user when successful signup.

but my code return anonymous user now

so, i use CreateView in django CBV

views.py

class SignUpView(CreateView):
  template_name = 'users/signup.html'
  success_url = reverse_lazy('users:email_confirm_notice')
  form_class = CustomUserCreationForm

  def form_valid(self, form):
    user = form.save()
    login(self.request, user)
    return super().form_valid(form)

and i try it

def form_valid(self, form):
  form.save()
  new_user = authenticate(username=form.cleaned_data.get('username'), password.cleaned_data.get('password1'))
  login(self.request, new_user)
  return super().form_valid(form)

success_url is TemplateView that is just display templates and customusercreationform change error message.

it is expected that there will be no changes from the first function.

What's my problem?

i solved it...

but i didn't understand why it worked this way.

I just change the code like below.

SignupView/form_vaild()

def form_valid(self, form):
    valid = super().form_valid(form)
    login(self.request, self.object)
    return valid

it's acting..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM