我对此有类似的问题 -
Conditional login redirect in Django
但我无法理解如何从答案中获得结果。
我对django比较新。我从某个地方重用了这个代码,将用户重定向到登录页面。但登录后我总是到达用户的开始/主页。我希望他们能够看到他们真正要求的页面,而不是用户主页。你能告诉我我可以在哪里和哪里做出改变,它应该是我使用“重定向”功能的地方。我可能应该保存一些会话变量并做到但不完全得到起点。有什么想法吗?
以下是代码 -
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
答案 0 :(得分: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
答案 1 :(得分:0)
在重定向中将URL作为GET参数传递,并让重定向目标在输入凭据后重定向它们。