skip to Main Content

I have an HTML table that I want to be populated from views.py. Here is my code:

index.html

{% for item in pizza %}
   <tr id="{{ item.name }}">
       <td>{{ item.status }}</td>
       <td>{{ item.name }}</td>           
   </tr>
{% endfor %}

views.py

def pizza(request):
   pizza_data = [{'name': 'Pepperoni Pizza', 'status': 'Ready'}]
   return render(request, "index.html", {'pizza': pizza_data})

The table doesn’t get populated and I don’t see any error code. Is it the format in pizza_data? I removed the other {% for %} loop because Lucas is right that the other loop is useless.

I think I should say that index.html is inside a folder named templates. Not sure if this will affect because I declared the STATIC_DIR into this folder.

The reason why pizza_data is hardcoded is because that is a JSON file that I need to figure out how to insert but for now I want to see if the {% for %} loop can populate but it is not.

4

Answers


  1. You have to rename your variable i think. And the second loop is useless, your put a dictionary in context, so you just need to access by key of each element:

    def pizza(request):
       pizza_data = [{'name': 'Pepperoni Pizza', 'status': 'Ready'}]
       return render(request, "index.html", {'pizzas': pizza_data})
    
    {% for pizza in pizzas %}
       <tr id="{{pizza.name}}">
           <td>{{pizza.status}}</td>
           <td>{{pizza.name}}</td>           
       </tr>
    {% endfor %}
    
    
    Login or Signup to reply.
  2. Use .items to loop through the dictionary:

    {% for obj in pizza %}
       <tr id="{{ obj.name }}">
           {% for key, value in obj.items %}
                <td>{{ value }}</td>
           {% endfor %}
       </tr>
    {% endfor %}
    
    Login or Signup to reply.
  3. Try this code it’s working

    views.py

    def pizza(request):
       pizza_data = [{'name': 'Pepperoni Pizza', 'status': 'Ready'}]
       return render(request, "index.html", {'pizza_data': pizza_data})
    

    HTML Table

    <table class="table ">
      <thead>
        <th>Item Name</th>
        <th>Status</th>
      </thead>
      <tbody>
        {% for item in pizza_data %}
        <tr id="{{ item.name }}">
          <td>{{ item.name }}</td>
          <td>{{ item.status }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    

    Output in Browser

    enter image description here

    Login or Signup to reply.
  4. Your code at least shows result, However If you get template does not exist error It has another solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search