将所有视图限制为Django中经过身份验证的用户 [英] Restricting all the views to authenticated users in Django

查看:50
本文介绍了将所有视图限制为Django中经过身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,我正在一个项目,该项目具有一个登录页面作为其索引和一个注册页面.其余页面都必须限制为登录用户,如果未经身份验证的用户尝试访问他们,则必须将其重定向到登录页面.

I'm new to Django and I'm working on a project which has a login page as its index and a signup page. The rest of the pages all must be restricted to logged in users and if an unauthenticated user attempts to reach them, he/she must be redirected to the login page.

我看到 @login_required 装饰器会将单个视图限制为登录用户,但是有没有更好的方法来限制所有视图,并且只有少数视图可供未经身份验证的用户使用?

I see that @login_required decorator would make a single view restricted to logged in users but is there a better way to make all the views restricted and only a few available to unauthenticated users?

推荐答案

您可以编写中间件:

from django.contrib.auth.decorators import login_required

def login_exempt(view):
    view.login_exempt = True
    return view


class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_view(self, request, view_func, view_args, view_kwargs):
        if getattr(view_func, 'login_exempt', False):
            return

        if request.user.is_authenticated:
            return

        # You probably want to exclude the login/logout views, etc.

        return login_required(view_func)(request, *view_args, **view_kwargs)

您将中间件添加到您的 MIDDLEWARES 列表中,并使用 login_exempt 装饰您不想验证的视图.

You add the middleware to your MIDDLEWARES list and decorate the views you don't want authenticated with login_exempt.

这篇关于将所有视图限制为Django中经过身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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