小编典典

在每个页面上放置一个django登录表单

django

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

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

是否有接受的方法?


阅读 400

收藏
2020-03-27

共1个答案

小编典典

好的,我最终找到了一种方法,尽管我确信还有更好的方法。我创建了一个新的中间件类,称为LoginFormMiddleware。在process_request方法中,或多或少使用auth登录视图的方式处理表单:

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

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

{{ request.login_form }}

请注意,在表单中添加了一个隐藏字段“ is_top_login_form”,因此我可以将其与页面上其他已发布的表单区分开。此外,表单动作为“。” 而不是auth登录视图。

2020-03-27