hi friends i need some help i want to redirect a user when he try to access a page in my django
settings.py is
MIDDLEWARE = ['cart.middleware.LoginRedirectMiddleware']
url.py is (home is the app name)
path('',views.login,name="login"),
path('home',views.home,name="home"),
middleware.py is (located in mainapp)
def process_view(self, request, view_func, view_args, view_kwargs):
"""
Called just before Django calls the view.
"""
print("executed")
if (request.user.is_authenticated):
return redirect('home')
else:
return redirect('login')
CodePudding user response:
The reason for your error is because your middleware only redirects the user in either outcome of the if-statement - so your code is constantly redirecting, even if they are taken to the home page - hence the ERR_TOO_MANY_REDIRECTS error.
What you need to do is specify that you want to redirect to 'home' if the user is authenticated AND trying to access the login page.
if (request.user.is_authenticated and request.path == '/login/'):
return redirect('home')
else:
return redirect('login')
Your actual request.path might look different, something like /accounts/login/ is also common.
CodePudding user response:
- I guess you have params in views.login / views.home?
If so, you should add args or kwargs in the back of redirect?
redirect('home', *args, **kwargs) - Use
return redirect('/some/url/')instead ofreturn redirect('home')
Ref:https://docs.djangoproject.com/en/4.0/topics/http/shortcuts/#redirect
Hope this could help
