【问题标题】:Django authenticationDjango 身份验证
【发布时间】:2010-05-16 04:48:10
【问题描述】:

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

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

现在当我点击log in 链接时,它会显示用户名以及正常的登录视图,表示用户已登录。

那么,怎么了?

【问题讨论】:

    标签: django django-templates django-authentication


    【解决方案1】:

    听起来您的模板中没有任何用户信息。您需要在 MIDDLEWARE_CLASSES 设置中使用 'django.contrib.auth.middleware.AuthenticationMiddleware',并且要在模板的上下文中获得这种优势,您需要这样做:

    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))
    

    【讨论】:

    • 谢谢,Dominic R。还有一件事,所以,我需要在我的所有视图中包含context_instance,如果我需要总是这样做(比如在标题中显示“登录”信息) )?如果我一直想做这件事,难道没有更好的方法吗?我希望我很清楚。
    • @webvulture - 看看 django-annoying(见我的编辑)。我知道关于 render_to 装饰器是否邪恶的观点各不相同,但我倾向于觉得它很有用。如果您的视图除了渲染到该模板之外还会做任何事情,请不要使用它。
    【解决方案2】:

    我相信 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, ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 2011-09-23
      • 2013-09-09
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多