如何在Django的base.html中检查用户是否已认证?
如果用户是匿名的还是登录的,我该怎么在base.html里检查呢?
哪个写法是对的?
{% if request.user.is_authenticated %}
或者
{% if user.is_authenticated %}
我该怎么把变量 request.user
传到base.html里呢?
1 个回答
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
,这样每次渲染模板时都会自动传递一个请求上下文:
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#module-django.shortcuts