用户注册后Django自动登录(2.1.4) [英] Django automatic login after user registration (2.1.4)
本文介绍了用户注册后Django自动登录(2.1.4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在基于类"的注册视图中,新注册用户的自动登录不起作用.
The automatic login of newly registered users is not working in the case of a "class-based" registration view.
我遵循了本教程中的示例,其中提出了以下建议注册视图:
I followed the example from this tutorial, which proposes the following registration view:
# myapp/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
我尝试包括此答案中的基于类的解决方案,但在成功注册新用户后,登录名却没有不会按预期发生.Django 2.1.4中是否有可能导致此故障的更改?
I tried including the class-based solution from this answer, but after successfully registering a new user, the login doesn't happen as expected. Are there changes in Django 2.1.4 which might cause this to malfunction?
myapp.users.views
:
from django.views import generic
from django.contrib.auth import authenticate, login
from .forms import CustomUserCreationForm
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = '/index'
template_name = 'signup.html'
#auto login after register:
def form_valid(self, form):
#save the new user first
form.save()
#get the username and password
username = self.request.POST['username']
password = self.request.POST['password1']
#authenticate user then login
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'],)
login(self.request, user)
return super(SignUp, self).form_valid(form)
推荐答案
注册后已通过此行登录
login(self.request, user)
您可能需要重定向主页.所以,您需要更改此行
You may need to redirect homepage. SO, you need to chnage this line
return super(SignUp, self).form_valid(form)
到
return HttpResponseRedirect(reverse('url_name'))
这篇关于用户注册后Django自动登录(2.1.4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文