且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在每个页面上添加一个django登录表单

更新时间:2023-11-24 13:05:28

好的,我最终找到了一个这样做的方法,虽然我确定有更好的方法。我创建了一个名为LoginFormMiddleware的新的中间件类。在process_request方法中,或多或少地处理auth登录视图的方式:

Ok, I eventually found a way of doing this, although I'm sure there are better ways. I created a new middleware class called LoginFormMiddleware. In the process_request method, handle the form more or less the way the auth login view does:

class LoginFormMiddleware(object):

    def process_request(self, request):

        # if the top login form has been posted
        if request.method == 'POST' and 'is_top_login_form' in request.POST:

            # validate the form
            form = AuthenticationForm(data=request.POST)
            if form.is_valid():

                # log the user in
                from django.contrib.auth import login
                login(request, form.get_user())

                # if this is the logout page, then redirect to /
                # so we don't get logged out just after logging in
                if '/account/logout/' in request.get_full_path():
                    return HttpResponseRedirect('/')

        else:
            form = AuthenticationForm(request)

        # attach the form to the request so it can be accessed within the templates
        request.login_form = form

现在,如果您安装了请求上下文处理器,则可以使用以下格式访问该表单:

Now if you have the request context processor installed, you can access the form with:

{{ request.login_form }}

请注意,隐藏字段'is_top_login_form'被添加到表单中,所以我可以将其与页面上的其他帖子区分开来。此外,表单动作是。而不是auth登录视图。

Note that a hidden field 'is_top_login_form' was added to the form so I could distinguish it from other posted forms on the page. Also, the form action is "." instead of the auth login view.