需要登录的装饰器和Django会话

时间:2018-09-20 12:32:02

标签: python django

我正在按会话在Django中以用户身份登录,我使用文件来保存会话。当用户登录时,它会创建一个会话,而在注销时,它将删除该会话,我想停止用户访问“ URL”(仅在登录后才可用)。但是当我使用登录名时,它无法识别“已登录”在用户会话中”,并因为我在定义函数时在login_required装饰器中给出了login_url = 'home'而将我重定向到主页。那么,如何使我的装饰器识别登录的会话?

1 个答案:

答案 0 :(得分:1)

不确定使用登录必需的装饰器时为什么无法识别登录的用户会话。您可以使用以下装饰器来访问会话,用户和重定向。

def custom_login_required(function):
    def wrap(request, *args, **kwargs):
        session = request.session # this is a dictionary with session keys
        user = request.user
        if user.is_authenticated:
            # the decorator is passed and you can handle the request from the view
            return function(request, *args, **kwargs)
        else:
            return redirect('login')


    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap