Reputation: 33
How can I do, whole urls for my site available only for register user. I use Middleware, but this class doesn't work
I use Django==2.1.4
class MyAuthorization:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
def process_request(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/') # or http response
return None
settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myapp.middleware.MyAuthorization',
]
Upvotes: 1
Views: 515
Reputation: 31514
The process_request
method in your middleware class will never get called - there is nothing in Django that calls such a method. You need to perform that logic in the __call__
method itself, before calling get_response()
- something like this:
class MyAuthorization:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.user.is_authenticated: # Note, this is a property, not a method
if not request.path == '/':
return HttpResponseRedirect('/')
response = self.get_response(request)
return response
Note the second if
statement - if not request.path == '/'
- this is to ensure that you don't get an infinite redirect. You probably need to use similar logic to exclude your login views from this check, otherwise a logged-out user would never be able to reach it.
Upvotes: 2
Reputation: 14360
As @solarissmoke states, you should use __call__
instead of process_request
.
def __call__(self, request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
Also if the user is not authenticated you are just redirecting to '/', that can give the impression nothing is happening.
Perhaps you should redirect to whatever is your login view.
Upvotes: 0