2011-05-12 45 views
0

我正在使用登錄中間件創建用戶登錄表單。Django檢索會話用戶標識

用戶成功登錄後,從視圖中檢索用戶標識的最佳方法是什麼?

創建一個middleware.py:

class LoginMiddleware(object): 
    def process_request(self, request): 
     if request.path != self.require_login_path and request.user.is_anonymous(): 
      if request.POST: 
       return login(request) 
      else: 
       return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path)) 
+1

等等,正常的auth中間件又出了什麼問題? – 2011-05-12 15:33:18

+0

它沒有錯,我面對的問題是從視圖或模板登錄後檢索用戶ID。 – kelvinfix 2011-05-13 00:27:42

回答

5

一旦用戶登錄,他們的相關User對象通過request.user,請在您的模板,自動。當你說「用戶ID」時,我不確定你的意思是用戶名或數據庫中的文字值id。儘管如此,相同的方法適用於:{{ request.user.username }}{{ request.user.id }}

此外,正如上面提到的評論者所說,除非您需要更改登錄處理方式中的某些內容,否則沒有理由創建新的身份驗證中間件。否則,請保持獨立並使用默認值。 (這似乎是你應該根據你的中間件做什麼)。

更新:忽略提及,要訪問您的模板request.user,您必須通過RequestContext。示例render_to_response以下:

from django.template import RequestContext 

render_to_response('templates/mytemplate.html', {}, context_instance=RequestContext(request)) 
+0

感謝克里斯的答案。我會試試看。 – kelvinfix 2011-05-13 00:28:35

+0

他可能需要將RequestContext傳遞給模板,對嗎? – 2011-05-13 03:38:03

+0

我需要在視圖中的用戶ID從數據庫檢索數據。 – kelvinfix 2011-05-13 05:37:40