使用Django的render_to_response时总是匿名用户

0 投票
2 回答
1143 浏览
提问于 2025-04-17 05:44

我正在使用Django 1.3.1。在我的Django代码中,有一个主页面的模板,叫做main_page.html:

<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Welcome</h1>
{% if user.username %}
   <p>Welcome {{ user.username }}!</p>
{% else %}
   <p>Welcome anonymous user!
   You need to <a href="/login/">login</a>
{% endif %}
</body>
</html>

我为这个模板写了以下视图:

def main_page(request):
  template = get_template('main_page.html')
  variables = Context({'user': request.user})
  output = template.render(variables)
  return HttpResponse(output)

这个视图的功能是正常的,也就是说,它会检查用户是否已经登录,并根据情况进行问候。但是,如果我把上面的视图换成下面的代码,那么无论我是否登录,主页面上总是会显示匿名用户的消息。

def main_page(request):
  return render_to_response(
      'main_page.html',
       {'user': request.user}
  )

这里可能出了什么问题呢?请帮帮我。

谢谢

2 个回答

0

我也不太明白为什么这样不行。你在视图里用的用户变量确定是正确的吗?(可以试着把它打印到控制台,或者用调试工具看看)。有没有可能是因为请求上下文已经在用的情况下,认证上下文处理器已经把user加到了你的上下文里?

从Django 1.3开始,有一个新的快捷方式render

render(request, template, dictionary)

如果你只是想省点打字的话

4

在模板里,你应该用 {% if request.user.is_authenticated %} 这个来代替你原来的 {% if user.username %}。这样应该能解决你的问题。

另外,我不太明白你为什么要在视图里明确添加 user 这个变量。为什么不试试用类似这样的方式呢:

def main_page(request):
  return render_to_response(
      'main_page.html',
       context_instance=RequestContext(request)
  )

撰写回答