2011-03-14 127 views
8

嗨 我遇到了Django模板系統的問題。當我想在模板檢查,如果用戶使用登錄:Django request.user.username不起作用

{% if user.is_authenticated %} 
    # success 
{% else %} 
    <p>Welcome, new user. Please log in.</p> 
{% endif %} 

我不明白的成功的一部分。當我在一個視圖中使用:

if not request.user.is_authenticated(): 
    return render_to_response('index.html', {'inhalt': 'Not loggged in'}) 
else: 
    return render_to_response('index.html', {'inhalt': 'Succesfully loged in'}) 

它正確地顯示我的其他部分。 希望有人能幫助我。 感謝菲爾

回答

9

還有就是在part 4 of the Django tutorial.處理上下文然而,在很短的例子...

做到這一點,最好的辦法是與Django的權威性方面proccessor。確保你仍然在your settings。然後您需要使用RequestContext

這實際上會將您的代碼更改爲此。

from django.template import RequestContext 
# ... 
return render_to_response('index.html', { 
    'inhalt': 'Succesfully loged in' 
}, RequestContext(request)) 
+0

THX工作現在終於。 – Philip 2011-03-14 17:23:45

+0

使用direct_to_template也可以工作 – goh 2012-02-28 15:04:26

1

您是否將您的「用戶」實例從視圖傳遞到模板?您需要確保它處於與render_to_response()相同的上下文中,或者您選擇將視圖上下文呈現到模板中的任何呈現方法。

2

您需要確保將「request.user」傳遞給渲染器。或者更好的是使用基於情境的渲染:

return render_to_response('index.html', 
          my_data_dictionary, 
          context_instance=RequestContext(request)) 

的context_instance將使用身份驗證的中間件上下文處理器設置視圖中的「用戶」。

3

在您的python中檢索登錄的用戶對象。I.e定義函數get_current_user。

所以你的反應會是這個樣子:

class Index(webapp.RequestHandler): 
    def get(self): 
    user= get_current_user() 
    templates.render(self, 'mypage.html', user=user) 

然後在你的Django模板,你可以簡單地去喜歡:

{% if user %} 
    <p>Hallo user {{user.name}}</p> 
{% else %} 
    <p>Welcome, new user. Please log in.</p> 
{% endif %} 
+1

+1與{{request.user}}變量不同,{{user}}變量默認可用。對於後者,你必須啓用'django.core.context_processors.request'。我發現現在的Django版本更好,儘管http://stackoverflow.com/a/5301918/781695也是正確的。 – Medorator 2014-04-07 12:04:32

6

記住添加'django.core.context_processors.request'在你的settings.py你TEMPLATE_CONTEXT_PROCESSORS

例子:

# Context processors 
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth', 
    'django.core.context_processors.debug', 
    'django.core.context_processors.i18n', 
    'django.core.context_processors.media', 
    'django.core.context_processors.static', 
    'django.core.context_processors.request', 
    'django.contrib.messages.context_processors.messages', 
) 

並添加RequestContext的(要求):

# import 
from django.template import RequestContext 

# render 
if not request.user.is_authenticated(): 
    return render_to_response('index.html', {'inhalt': 'Not loggged in'}) 
else: 
    return render_to_response('index.html', {'inhalt': 'Succesfully logged in'}, RequestContext(request))