【问题标题】:How can i check if the user is authenticated or not in base.html in django?如何在 django 的 base.html 中检查用户是否经过身份验证?
【发布时间】:2012-02-06 23:28:08
【问题描述】:

如果用户匿名与否,我如何在 base.html 中检查?

哪个是正确的?

{% if request.user.is_authenticated %}

或者

{% if user.is_authenticated %}

如何在 base.html 中传递变量 request.user

【问题讨论】:

    标签: python django templates authentication


    【解决方案1】:

    尝试使用请求上下文:

    from django.template import RequestContext
    
    # in a view
    return render_to_response('base.html', context_instance = RequestContext(request))
    

    请务必查看以下上下文处理器:https://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-context-processors-auth

    然后你应该可以在你的模板中访问user

    您可以使用 django 快捷方式 render 始终呈现自动传递 RequestContent 的模板:

    https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#module-django.shortcuts

    【讨论】:

    • 所有模板扩展 base.html 并且您没有在那里传递任何上下文。那么我必须以这种方式传递每个视图方法吗? return render_to_response('base.html',{'user': request.user, context_instance = RequestContext(request)) 在每个视图方法中传递 request.user 并不是一个好主意。
    • 你不需要显式地传入用户对象。它将通过传递一个 RequestContext 来提供。您可以在需要将请求传递到模板的视图中执行此操作。
    • base.html 是整个项目通用的,base.html 需要检查它是否是登录用户,基于它会打印登录或注销锚链接。
    • 查看我的最新更新以使用render 快捷方式。是的,您的响应需要始终包含一个 RequestContext,默认情况下会这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多