-3

here is my middleware file in 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)

here is my error : if not request.user.is_authenticated(): TypeError: 'bool' object is not callable please somebody help me with that

panti
  • 21
  • 6
  • 1
    `is_authenticated` is an attribute. So you shouldn't be calling it. Try: `if request.user.is_authenticated and url_is_exempt`. See: https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#attributes – Harun Yilmaz Nov 16 '21 at 08:37

1 Answers1

2

Just change

if not request.user.is_authenticated():

to

if not request.user.is_authenticated:

As mentioned in the above comment, is_authenticated is an attribute, not a function. So you can't call it.

Read: Difference between methods and attributes in python

Sumithran
  • 6,217
  • 4
  • 40
  • 54