2012-02-06 40 views

回答

1

嘗試使用請求上下文:

from django.template import RequestContext 

# in a view 
return render_to_response('base.html', context_instance = RequestContext(request)) 

確保你看看這方面處理器:https://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-context-processors-auth

然後你應該能夠訪問user在模板

你可以使用django快捷鍵render來始終呈現自動通過RequestContent的模板:

https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#module-django.shortcuts

+0

所有模板擴展'base.html',並且您沒有傳遞任何上下文。那麼我是否必須以這種方式傳遞每個視圖方法? 'return render_to_response('base.html',{'user':request.user,context_instance = RequestContext(request))'在每個視圖方法中傳遞'request.user'不是個好主意。 – shibly 2012-02-06 23:36:04

+0

您不需要顯式傳遞用戶對象。它將通過傳遞RequestContext來提供。您可以在需要將請求傳入模板的視圖中執行此操作。 – jdi 2012-02-06 23:52:13

+0

'base.html'對於整個項目來說很常見,在'base.html'中它需要檢查它是否是登錄用戶,基於它將打印登錄或註銷錨點鏈接。 – shibly 2012-02-06 23:56:27

相關問題