如何在Django view.py中向HTML传递对象?

问题描述 投票:2回答:3

我正在学习django & web开发,发现很难理解HTML如何接受请求和显示信息。

在下面的代码中,我想获取第一个图书对象(有两个属性'title''author'),然后把它传给display.html来显示图书对象的属性信息。当我尝试下面的代码时

def test_display(request):
    request = book.objects.all()[0]
    return render_to_response('display.html', RequestContext(request));

错误信息是这样显示的。

'book'对象没有属性'META'。

但在我的书中的models.py类中定义了META。这里的问题是什么?我是不是不应该传递对象作为请求?非常感谢您

python django django-views views
3个回答
4
投票

你不能把一个模型实例传递给 RequestContext因为 RequestContext 设计为与 HttpRequest 例。见 文件.

如果你想在模板中显示你的模型实例,只需在正常上下文中传递它,就像这样。

def test_display(request):
    book = book.objects.all()[0]
    return render_to_response('display.html', {'book': book})

然后你的模板就会变成这样

<ul>
  <li>{{ book.title }}</li>
  <li>{{ book.author }}</li>
</ul>

希望能帮到你


2
投票

呃,你使用的是 RequestContext 错了,它没有期待一个模型实例... 它没有期待一个模型实例... ...

删掉那行写着 request = book.objects.all()[0]

 def test_display(request):
         request = book.objects.all()[0]
         # ^^^^^^ you're redefining request
         return render_to_response('display.html', RequestContext(request));
                                                                         # ^ why;

另外,假设你是想使用RequestContext作为将你的书传递给模板的方式,你需要给它传递第二个参数,这个参数是一个上下文var名到值的字典。

RequestContext(request, {'book': book.objects.all()[0]})
© www.soinside.com 2019 - 2024. All rights reserved.