I’m developing a django project and my veiws are function based and using django-allauth for authentication. Now, I’m searching for a pattern to work on all project so that any unauthenticated user is redirected automatically to login page. An alternative way is to add @login_required() decorator over every view function but I don’t see that as logical method.
Asked
Active
Viewed 70 times
0
-
Did you try this : https://stackoverflow.com/a/64636245/8439435 – Benbb96 Apr 26 '23 at 08:52
-
Sorry, wrong answer, this one : https://stackoverflow.com/a/21123660/8439435 – Benbb96 Apr 26 '23 at 08:53
-
1That answer was good but with some modifications because after django 1.10 middlewares have changed a bit @Benbb96 – Youssef ElZawawy Apr 26 '23 at 11:57
1 Answers
1
With the help of @Benbb96 I discovered that the solution is using a custom middleware. I did some researches because after Django 1.10 middlewares initialization have changed.
Here's my code
from django.http import HttpResponseRedirect
from django.urls import reverse
class AuthRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
redirect_url = reverse("account_login")
if request.path == redirect_url:
return self.get_response(request)
if not request.user.is_authenticated:
return HttpResponseRedirect(redirect_url)
return self.get_response(request)
Added this to my settings.py
MIDDLEWARE = [
....
'MyApp.middlewares.AuthRequiredMiddleware'
]
Also see https://docs.djangoproject.com/en/3.2/topics/http/middleware/#upgrading-middleware
Benbb96
- 1,973
- 1
- 12
- 21
Youssef ElZawawy
- 23
- 6