重定向到/admin/login/结果为302 [英] Redirect to /admin/login/ results in 302
问题描述
当用户未通过身份验证时,我正在尝试重定向到登录页面.在我的 settings.py
类中,我有:
I'm trying to redirect to the login page when a user is not authenticated. In my settings.py
class I have:
MIDDLEWARE_CLASSES = [
'path.to.AuthRequiredMiddleware',
]
这是我的课程:
class AuthRequiredMiddleware(object):
def process_request(self, request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/admin/login/')
return None
但是,这始终会导致 [24/Jan/2017 14:09:07]当用户未通过身份验证时,"GET/admin/login/HTTP/1.1" 302 0
如何解决这个问题?无论重定向URL为何,更改都会导致相同的问题.
However this always results in [24/Jan/2017 14:09:07] "GET /admin/login/ HTTP/1.1" 302 0
when the user is not authenticated, does anyone know how to fix this? Changing the redirection URL results in the same issue no matter what it is.
我也尝试过使用 django.shortcuts导入重定向
,但是从中我也得到了相同的 302
结果.
I have also tried to use the django.shortcuts import redirect
however I got the same 302
result as well from it.
推荐答案
如果这是您的全部代码,那么您总是会陷入重定向循环.
If this is your whole code then you always end up in a redirect loop.
- 用户未登录并转到
/
由于应该有一个登录表单,因此 - 用户被重定向到
/admin/login
- 用户登陆到
/admin/login
,但仍未登录,被重定向到/admin/login
- 无限期重复步骤3.
- user is not logged in and goes to
/
- user is redirected to
/admin/login
since there should be a login form - user lands on
/admin/login
but is still not logged in, gets redirected to/admin/login
- repeat step 3. indefinitely
因此/admin/login
应该是一个例外,用户可以在未登录时获取该信息.
So /admin/login
should be an exception where user can get when he is not logged in.
类似这样的东西:
class AuthRequiredMiddleware(object):
def process_request(self, request):
redirect_url = '/admin/login'
if not request.user.is_authenticated() and request.path != redirect_url:
return HttpResponseRedirect(redirect_url)
return None
这篇关于重定向到/admin/login/结果为302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!