2013-02-11 20 views
11

我如何獲得當前用戶在Django模板標籤? (請求對象不可訪問) 或者我如何訪問請求對象?如何讓模板標籤中的當前用戶?

+0

您可以將其創建爲背景處理器比創建模板標籤和模板,隨時調用它。在上下文處理器中,您可以在不調用模板中的函數的情況下始終獲取用戶。 – catherine 2013-02-11 15:11:20

+0

真的很複雜的單線模板標籤..真的django如此不方便嗎? – tapioco123 2013-02-11 15:14:08

+2

或者試着把它放在你的模板{{user.username}} – catherine 2013-02-11 15:14:35

回答

11

如果要訪問當前用戶的模板標籤,你必須把它作爲一個參數模板,像這樣:

{% my_template_tag user %} 

然後確保你的模板標籤接受這個額外的參數。查看關於此主題的documentation。您還應該查看simple tags

9

用戶總是附在請求,在你的模板,您可以執行以下操作:

{% if user.is_authenticated %} 
{% endif %} 

您不必指定「請求」即可訪問其內容

更新:

注意:is_authenticated()總是登錄的用戶(User對象)返回True,但返回False 10(訪客用戶)。在這裏閱讀:https://docs.djangoproject.com/en/1.7/ref/contrib/auth/

+4

關閉主題 – tapioco123 2013-02-11 15:19:45

+0

'user.is_authenticated'總是返回true,所以它基本上是無用的。 – 2015-01-28 10:26:37

+0

不!對於User(記錄的),它總是返回true,但對於AnonymousUser返回false,所以不是無用的!請仔細閱讀此處:https://docs.djangoproject.com/en/1.7/ref/contrib/auth/ – daveoncode 2015-01-29 08:25:19

0

這個問題已經answered here

{% ifuser.is_authenticated %} 
    Welcome 
'{{ user.username }}' 
    {% else %} 
    <a href="{% url django.contrib.auth.login %}">Login</a> 
{% endif %} 

,並確保你已經安裝在你的settings.py請求模板,背景處理器:

TEMPLATE_CONTEXT_PROCESSORS = (
... 
'django.core.context_processors.request', 
... 
) 

注:

  • 使用request.user.get_username() in views & user.get_username in 模板。優先直接引用用戶名屬性。 Source
  • 如果使用RequestContext,則此模板上下文變量可用。
  • django.contrib.auth.context_processors.auth默認情況下啓用&包含變量用戶
  • 你並不需要啓用django.core.context_processors.request模板背景處理器。

來源:https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates

相關問題