Django身份验证

时间:2010-05-16 04:48:11

标签: django django-templates django-authentication

在我的base.html文件中,我正在使用
{% if user.is_authenticated %}
<a href="#">{{user.username}}</a>
{% else %} <a href="/acc/login/">log in</a>

在这里,即使用户已登录,也会显示登录按钮。

现在当我点击log in链接时,它会显示用户名和普通登录视图,说明用户已登录。

那么,出了什么问题?

2 个答案:

答案 0 :(得分:5)

听起来您没有在模板中获取任何用户信息。您需要在'django.contrib.auth.middleware.AuthenticationMiddleware'设置中MIDDLEWARE_CLASSES,并且要在模板的上下文中获得好处,您需要执行以下操作:

from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view(request):
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

为了节省您在任何地方执行此操作,请考虑使用django-annoying's render_to装饰器而不是render_to_response

@render_to('template.html')
def foo(request):
    bar = Bar.object.all()
    return {'bar': bar}

# equals to
def foo(request):
    bar = Bar.object.all()
    return render_to_response('template.html',
                              {'bar': bar},
                              context_instance=RequestContext(request))

答案 1 :(得分:1)

我相信Dominic Rodger的答案可以解决您的问题。只是想补充一点,我个人更喜欢导入direct_to_template而不是render_to_response

from django.views.generic.simple import direct_to_template
...
return direct_to_template(request, 'my_template.html', my_data_dictionary)

但我想这只是一个品味问题。在我的情况下,您也可以使用命名参数而不是my_data_dictionary

return direct_to_template(request, 'template.html', foo=qux, bar=quux, ...)
相关问题