2011-01-05 48 views
4

我已經與這一個搏鬥了一下,並用Google搜索了一遍,所以我猜它有時間去問。我試圖讓我的應用程序重定向到登錄後最後查看的頁面。我正在運行django 1.2.4,迄今爲止沒有運氣。登錄後重定向到最後一個視圖

這個堆棧溢出線程好像它會做的伎倆,但我還沒有成功,與它://本地主機:1100從我重定向到任何視圖登錄後 Django: Redirect to previous page after login ...

目前/帳號/資料/

settings.py有這個建議代碼: 「django.core.context_processors.request」,

以此作爲我的登錄按鈕鏈接: <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">login</a>

我也確信導入的RequestContext在我views.py文件: 從django.template進口的RequestContext

我得到這是行不通的印象。我也注意到現在 登錄網址中有一個部分下一個網址: // localhost:1100/accounts/login /?next =

建議? 在此先感謝!

回答

4

如果您在視圖上使用login_required裝飾器,它會自動爲您執行此操作。

這是由經驗所證實,並在文檔解釋說:

如果用戶沒有登錄,重定向到 settings.LOGIN_URL,路過 當前絕對路徑查詢 字符串。例如: /accounts/login /?next =/polls/3 /。

+0

感謝sdolan,所以我是用我的觀點類似這樣的文字裝飾:@login_required 高清wine_review_page(請求,wine_id):這是不正確的方式去嗎?我不知道如何設置下一個鏈接,我猜。 – bmartinek 2011-01-07 05:35:48

5

正如sdolan說,你可以使用login_required裝飾,但也有一些更possiblities:

  • 表單操作:

    <form method="post" action="{% url django.contrib.auth.views.login %}?next={{request.path}}"> 
    
  • 下一個隱藏字段:

    <input type="hidden" name="next" value="{{request.path}}" /> 
    
  • With al墨到登錄表單:

    <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a> 
    

對於使用它們,則必須通過請求上下文中的相應視圖。這樣的例子可以在這裏找到:http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

+0

+1如果您使用的是django股票登錄系統,則此方法爲'href =「{%url django.contrib.auth.views.login%}?next = {{request。}}「> Login'是最可靠的一個imo,其他兩種方法由於[**這個bug **](https://stackoverflow.com/q/22288861/4334743)而存在問題。 – AneesAhmed777 2017-08-18 16:24:18