django在页面模板里使用用户信息

django在页面模板里使用用户信息,参考http://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext
首先在settings.py里定义

django在页面模板里使用用户信息
参考http://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext
首先在settings.py里定义
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages")
[/ccn]
其中django.contrib.auth.context_processors.auth是必须的
然后在view里的方法里加上context_instance=RequestContext(request),比如下面的
# 索引页
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
if request.method == 'GET':
latest_project_list = Project.objects.all().order_by('-create_date')[:20]
return render_to_response('mark/projects.html',
{'latest_project_list': latest_project_list},
context_instance=RequestContext(request))
[/ccn]
因为这些信息是经过模板上下文过滤器(或者叫中间件,在前面settings.py里定义的) ,定义在RequestContext里的
这样页面里就默认有user这个变量了
使用方法如下
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}
[/ccn]