【发布时间】: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
如果用户匿名与否,我如何在 base.html 中检查?
哪个是正确的?
{% if request.user.is_authenticated %}
或者
{% if user.is_authenticated %}
如何在 base.html 中传递变量 request.user?
【问题讨论】:
标签: python django templates authentication
尝试使用请求上下文:
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 并不是一个好主意。
base.html 是整个项目通用的,base.html 需要检查它是否是登录用户,基于它会打印登录或注销锚链接。
render 快捷方式。是的,您的响应需要始终包含一个 RequestContext,默认情况下会这样做。