在Django注册后如何自动登录用户
这是我目前用于注册的内容:
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))
是否可以不要求用户在创建帐户后手动登录,而是简单地自动登录?谢谢。
编辑:我曾尝试过login()函数,但没有成功。我相信问题是未设置AUTHENTICATION_BACKENDS。
回答:
使用authenticate()和login()功能:
from django.contrib.auth import authenticate, logindef 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注册后如何自动登录用户 的全部内容, 来源链接: utcz.com/qa/420041.html