2011-11-06 46 views
0

即時通訊使用Django 1.3.1.In我的Django的代碼,我對主網頁下面的模板,其所謂的main_page.html:始終匿名用戶使用Django的代碼時選擇render_to_response

<html> 
<head> 
<title>My Site</title> 
</head> 
<body> 
<h1>Welcome</h1> 
{% if user.username %} 
    <p>Welcome {{ user.username }}!</p> 
{% else %} 
    <p>Welcome anonymous user! 
    You need to <a href="/login/">login</a> 
{% endif %} 
</body> 
</html> 

我有對此模板的以下視圖:

def main_page(request): 
    template = get_template('main_page.html') 
    variables = Context({'user': request.user}) 
    output = template.render(variables) 
    return HttpResponse(output) 

此功能按預期工作,即它檢查用戶是否已經登錄並且相應地打招呼。但是,如果我用下面的代碼替換上述視圖,那麼無論我是否已登錄,我都會在主頁上獲取匿名用戶的消息。

def main_page(request): 
    return render_to_response(
     'main_page.html', 
     {'user': request.user} 
) 

這裏可能會出現什麼問題?請幫忙。

謝謝

+0

我看不到任何原因此行爲。我用你的視圖函數創建了一個測試項目,並且不能重現你的問題。你使用的是什麼django版本?檢查你的代碼 - 也許你忘了告訴我們一些重要的東西? –

回答

4

在模板中,你應該使用{% if request.user.is_authenticated %}而不是你的{% if user.username %}的。這應該可以解決你的問題。

另一方面,我不知道,爲什麼你要在視圖中明確添加user變量。爲什麼不使用類似的東西:

def main_page(request): 
    return render_to_response(
     'main_page.html', 
     context_instance=RequestContext(request) 
) 
+0

感謝您的回覆。但即時通過您所提出的修改,我依然面臨着這個問題。不知道爲什麼render_to_response無法正常工作。我已經從django.template導入Context,RequestContext和從django.shortcuts導入render_to_response了。還有什麼我可以嘗試? – JoeRP

+1

更好的是,使用['render()'](https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#render),它會自動呈現一個RequestContext。 –

+1

這很奇怪。你有沒有嘗試過使用Django Debug Toolbar應用程序?它會顯示你的模板變量在訪問主頁時的確切內容。鏈接:http://pypi.python.org/pypi/django-debug-toolbar/ –

0

不知道爲什麼這樣不起作用。用戶變量在視圖中絕對正確嗎? (嘗試將其打印到控制檯或放入調試器中)。是否可以使用請求上下文,因爲auth上下文處理器已經將user添加到您的上下文中了?

爲Django的1.3,有一個新的快捷方式render

render(request, template, dictionary) 

,如果你只是希望節省上鍵入

+0

我在我的main_page視圖中打印了request.user。它可以正確顯示控制檯中的當前用戶。但是由於一些奇怪的原因,這個模板沒有正確傳達給你! :( – JoeRP

+0

正在使用例如渲染不是一個選項? – second