首页 > 解决方案 > 为什么'bool'对象不可调用

问题描述

这是我在 django 中的中间件文件

import re

from django.conf import settings
from django.shortcuts import redirect

EXEMPT_URL = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URL += [re.compile(url)for url in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:

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

    def __call__(self,request):
        response = self.get_response(request)
        return response
    
    def process_view(self,request, view_func, view_args, view_kwargs):
        assert hasattr(request,'user')
        path = request.path_info
        print(path)
    
        if not request.user.is_authenticated():
            if not any (url.match(path) for url in EXEMPT_URL):
                return redirect(settings.LOGIN_URL)
        
        url_is_exempt = any (url.match(path) for url in EXEMPT_URL)

        if request.user.is_authenticated() and url_is_exempt:
            return redirect(settings.LOGIN_REDIRECT_URL)
        elif request.user.is_authenticated() or url_is_exempt:
            return None
        else:
            return redirect(settings.LOGIN_URL)

这是我的错误:如果不是 request.user.is_authenticated(): TypeError: 'bool' object is not callable 请有人帮我

标签: django

解决方案


只是改变

if not request.user.is_authenticated():

if not request.user.is_authenticated:

正如上面评论中提到的,is_authenticated是一个属性,而不是一个函数。所以你不能调用它。

阅读:python中方法和属性的区别


推荐阅读