简体   繁体   English

如何在 Django view.py 中将对象传递给 HTML

[英]How to pass an object to HTML In Django view.py

I am learning django & web development and find it hard to figure out how the HTML takes request and display information.我正在学习 django 和 web 开发,发现很难弄清楚 HTML 如何获取请求和显示信息。

In the below code, I want to get the first book object(with two attribute 'title''author') and pass it to the display.html to display the attribute info of the book object.在下面的代码中,我想获取第一个 book 对象(具有两个属性 'title''author')并将其传递给 display.html 以显示 book 对象的属性信息。 When I am trying the code below当我尝试下面的代码时

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

Error message is displayed like this.错误信息是这样显示的。

'book' object has no attribute 'META' 'book' 对象没有属性 'META'

But in my book class in the models.py META is defined.但是在我的书类中,models.py META 是定义的。 What is the problem here?这里有什么问题? Am i not supposed to pass the object as request??我不应该将对象作为请求传递吗? Thank you very much非常感谢

You cannot pass a model instance to RequestContext , because RequestContext was designed to work with HttpRequest instance.您不能将模型实例传递给RequestContext ,因为RequestContext旨在与HttpRequest实例一起使用。 See documentation .请参阅文档

If you want to display your model instance in the template, just pass it in the normal context, like this:如果你想在模板中显示你的模型实例,只需在普通上下文中传递它,就像这样:

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

Then your template can look like this:然后你的模板看起来像这样:

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

Hope that helps.希望有帮助。

Uh, you're using RequestContext wrong.呃,你使用RequestContext错误的。 It's not expecting a model instance...它不期待模型实例......

Remove the line that says request = book.objects.all()[0]删除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;

Also assuming you were trying to use RequestContext as a way to pass your book to the template, you need to pass it a second argument which is a dictionary of context var names to values.还假设您尝试使用 RequestContext 作为将您的书传递给模板的一种方式,您需要将第二个参数传递给它,该参数是上下文变量名称到值的字典。

RequestContext(request, {'book': book.objects.all()[0]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM