Django 正确重定向的方法?
我有一个类似的问题,具体可以参考这个链接:
Django中的条件登录重定向
不过我看不太懂那里的回答是怎么实现的。
我对Django还比较陌生。我从别的地方拿了段代码,这段代码会把用户重定向到登录页面。但是登录后,我总是被带到用户的主页。我希望他们能看到他们真正请求的页面,而不是总是回到用户的主页。你能告诉我该在哪儿做修改吗?应该是在我使用'redirect'函数的地方。我可能需要保存一些会话变量,但我不太清楚该从哪里开始。你有什么想法吗?
下面是代码 -
def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
if test_func(request.user): # Already logged in, just return the view.
return view(request, *args, **kwargs)
# They are not logged in. See if they provided login credentials
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
# NOTE: We are only support basic authentication for now.
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user is not None:
if user.is_active:
login(request, user)
request.user = user
return view(request, *args, **kwargs)
# Either they did not provide an authorization header or something in the authorization attempt failed. Send a 401 back to them to ask them to authenticate.
key = request.path.split('/')
if len(key) > 1:
base_url = request.get_host()
return redirect( 'https://' + base_url + '/login/')
s = '401 Unauthorized'
response = HttpResponse(s)
response.status_code = 401
response['Content-Length'] = '%d' % len(s)
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return response
2 个回答
0
把网址作为一个GET参数放在重定向中,然后让重定向的目标在用户输入完凭证后再把他们引导回来。
1
这很简单:
在你的重定向链接中添加一个GET参数,这样你的登录页面就知道用户是从哪里来的。这个参数可以是任何东西,我这里用的是 "?redirect=myurl"
。
在你的登录页面中:在用户成功登录后,检查一下GET参数中是否有这个键(redirect
)。如果有,就根据这个值进行重定向。
首先修改你的重定向链接:
# add a GET parameter to your redirect line that is the current page
return redirect( 'https://' + base_url + '/login/?redirect=%s' % request.path )
然后在你的登录页面中,只需检查GET参数中是否有这个变量,如果有,就根据这个值进行重定向。
# modify the login view to redirect to the specified url
def login(request):
# login magic here.
if login_successful:
redirect = request.GET.get('redirect') # get url
if redirect:
# redirect if a url was specified
return http.HttpResponseRedirect(redirect)
# otherwise redirect to some default
return http.HttpResponseRedirect('/account/home/')
# ... etc