简体   繁体   English

如何将Django模型内容显示为html模板?

[英]How to display Django model content into html template?

I have a problem with displaying content from Model in Django. 我在Django中显示来自Model的内容时遇到问题。 I was created example model with one field which is "title" 我创建的示例模型的一个字段为“ title”

class Post(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
          return self.title

Then I am trying to create function in views.py which allow me to get objects from this field created in Django admin field, like this: 然后,我尝试在views.py中创建函数,该函数允许我从在Django管理字段中创建的该字段中获取对象,如下所示:

def post_title(request):
    title = Post.objects.all()
    context = {'titles': title}
    return render(request, 'home.html', context)

And I am trying to display it in html file using template: 我正在尝试使用模板在html文件中显示它:

{% extends "base.html" %}

{% block content %}
    <div class="container">
        <div class="row">
                <p>{{ titles.title }}</p>

        <div class="row">
            <div class="col col-sm-3">col 2</div>
            <div class="col col-sm-3">col 2</div>
            <div class="col col-sm-3">col 2</div>
            <div class="col col-sm-3">col 2</div>
        </div>
        <div class="row">
            <div class="col col-sm-3">col 3</div>
            <div class="col col-sm-3">col 3</div>
            <div class="col col-sm-3">col 3</div>
            <div class="col col-sm-3">col 3</div>
        </div>
    </div>
{% endblock %}

I would like to achieve displaying single string containt name of title in html. 我想实现在html中显示标题的单个字符串包含名称。

When you use all() it returns a QuerySets which is a list. 当您使用all()它返回一个QuerySets,它是一个列表。 You need to iterate through it and display. 您需要遍历并显示。

  {% for title in  titles %}
       <p> {{ title }} </p>
  {% endfor %}

So the above for loop is going to iterate through all your elements in the query. 因此,上面的for循环将遍历查询中的所有元素。

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

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