如何在django注册后自动login用户
这是我目前使用的注册:
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() messages.info(request, "Thanks for registering. Please login to continue.") return HttpResponseRedirect("/dashboard/") else: form = UserCreationForm() return render_to_response("accounts/register.html", { 'form': form, }, context_instance=RequestContext(request))
创build帐户后是否可以不要求用户手动login,而只是自动login? 谢谢。
编辑:我曾尝试login()函数没有成功。 我相信问题是没有设置AUTHENTICATION_BACKENDS。
使用authenticate()
和login()
函数:
from django.contrib.auth import authenticate, login def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() messages.info(request, "Thanks for registering. You are now logged in.") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return HttpResponseRedirect("/dashboard/")
对于基于类的视图,这里是我工作的代码(django 1.7)
from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.views.generic import FormView class SignUp(FormView): template_name = 'signup.html' form_class = UserCreateForm success_url='/account' 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=username, password=password) login(self.request, user) return super(SignUp, self).form_valid(form)