2011-03-14 126 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))