2010-12-08 66 views
0

我有一個類似的問題,這 -
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 
+0

您通常不應該使用基本身份驗證。除非通過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

回答

0

傳遞URL作爲重定向GET參數,並有重新導向的目標重定向他們回來,他們已經進入了他們的憑據後。

+0

我很抱歉,但我無法理解您的迴應,因爲我是一名新的django用戶。我應該在哪裏傳遞網址?我將如何重新引導它?謝謝! – Sujit 2010-12-13 20:59:17

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 
+0

你有沒有試過這個? – 2010-12-22 08:42:04