For loop to populate a django template table

I'm trying to make a table in Django template. I'm sending a dict as my data inside my views.py like this:

    data = {
    "year_most_launches": result_launches,
    "launch_sites":result_sites,
    "launches_2019_2021":result_2019_2021
    }
return render(request,"main/launches.html", {"data":data})

My table in HTML code:

            <table class="table">
            <thead>
                <tr>
                    <th>Year with most launches</th>
                    <th>Launch site with most launches</th>
                    <th>Number of launches between 2019 and 2021</th>
                </tr>
            </thead>
            <tbody>
                {% for element in data.values %}
                <tr>
                    <td>{{ element }}</td>
                </tr> 
                {% endfor %} 
            </tbody>
        </table>

My problem is that the values of data just appears in the first columm, creating 3 rows instead of just appearing in the first row.

table

How can I solve that? It is a problem inside my html?

Your HTML table is creating a new row (<tr>) for each element, what you want is to create a new cell, (<td>) for each each element, like this:

<table class="table">
  <thead>
      <tr>
          <th>Year with most launches</th>
          <th>Launch site with most launches</th>
          <th>Number of launches between 2019 and 2021</th>
      </tr>
  </thead>
  <tbody>

      <tr>
        {% for element in data.values %}
          <td>{{ element }}</td>
        {% endfor %}
      </tr>

  </tbody>
</table>

Of course, this will only produce ONE row, which may be what you want, but if you wanted several rows you would need two loops, an outer one for each <tr>, and an inner one for each <td>.

Back to Top