首页 > 解决方案 > 使用 django 提供的登录视图而不是自定义登录视图

问题描述

我正在开发一个 django 网站。我有自己的自定义用户模型。这是我的登录视图:

def login(request):

    if request.user.is_authenticated:
        return redirect('/')
    else:
        if request.method == "POST":
            email=request.POST['email']
            password=request.POST['password']
            user=auth.authenticate(email=email,password=password)

            if user is not None:
                auth.login(request, user)
                return redirect('/category/all')
            else:
                messages.info(request,"Email Password didn't match")
                return redirect('login')
        else:
            return render(request,"login.html")

我想转移到 django 提供的 login_view 以获得诸如登录后的下一步等功能,这在我的自定义视图中不会发生。因此,在我的网址中,我可以只使用登录视图,还是必须在模板和用户模型中进行一些更改,或者在拥有自定义用户模型后无法切换到预先提供的登录视图。

标签: pythondjango

解决方案


目前尚不清楚您如何将用户引导至登录页面。无论如何,在next变量中插入您希望用户返回的页面,例如:

<a href="{% url 'login' %}?next={{ request.path }}">login</a>

然后,在您的登录表单(模板)中添加一个额外的隐藏输入next

<input type="hidden" name="next" value="{{ request.GET.next }}">

next如果变量不为空,则在登录视图中将用户重定向到下一页:

if user is not None:
    auth.login(request, user)
    next_page = request.POST['next']
    if next_page != '':
        return redirect(next_page)
    else:
        return redirect('index')                
else:

推荐阅读