在每个页面上放置一个 django 登录表单 [英] Putting a django login form on every page

查看:32
本文介绍了在每个页面上放置一个 django 登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未登录,我希望登录表单(来自 django.contrib.auth 的 AuthenticationForm)出现在我网站的每个页面上.当用户登录时,他们将被重定向到同一页面.如果有错误,错误会和表单显示在同一个页面上.

I'd like the login form (AuthenticationForm from django.contrib.auth) to appear on every page in my site if the user is not logged in. When the user logs in, they will be redirected to the same page. If there is an error, the error will be shown on the same page with the form.

我想您需要一个上下文处理器来为每个模板提供表单.但是,那么您还需要每个视图来处理发布的表单吗?这是否意味着您需要创建一些中间件?我有点失落.

I suppose you'd need a context processor to provide the form to every template. But, then you'd also need every view to handle the posted form? Does this mean you need to create some middleware? I'm a bit lost.

有没有公认的方法来做到这一点?

Is there an accepted way of doing this?

推荐答案

好的,我最终找到了一种方法,尽管我确信还有更好的方法.我创建了一个名为 LoginFormMiddleware 的新中间件类.在 process_request 方法中,或多或少像 auth login 视图那样处理表单:

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",因此我可以将其与页面上其他已发布的表单区分开来.此外,表单操作是."而不是身份验证登录视图.

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.

这篇关于在每个页面上放置一个 django 登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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