0
votes

I have a problem with displaying content from Model in Django. I was created example model with one field which is "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:

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:

{% 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.

1

1 Answers

3
votes

When you use all() it returns a QuerySets which is a list. 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.