我有一個類似的問題,這 -
Conditional login redirect in DjangoDjango重定向正確的方式?
但我無法理解如何實現從答案有結果。
我對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
您通常不應該使用基本身份驗證。除非通過SSL進行加密,否則憑證將以*明文形式*在每個*請求上傳輸。對於大多數網站來說,這太脆弱了。 `django.contrib.auth`(http://docs.djangoproject.com/en/dev/topics/auth/)提供了一個基於會話的解決方案,非常適合大多數用戶,或者使用django-openid(https:///github.com/simonw/django-openid) – SingleNegationElimination 2010-12-15 00:55:02