如何在django中注册后自动登录用户 [英] How to automatically login a user after registration in django

查看:137
本文介绍了如何在django中注册后自动登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前用于注册的:

This is what I am currently using for registration:

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))

创建帐户后是否可能不需要用户手动登录,而只是自动登录?谢谢。

Is it possible not to require the user to login manually after creating an account, but rather simply to log them in automatically? Thanks.

编辑:我没有成功尝试过login()函数。我认为问题是AUTHENTICATION_BACKENDS未设置。

edit: I had tried the login() function without success. I believe the problem is that AUTHENTICATION_BACKENDS was not set.

推荐答案

使用 authenticate() login() 功能:

Using the authenticate() and login() functions:

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中注册后自动登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆