Skip to content
Advertisement

Django Render List of Dictionaries to a template

I have a list of dictionaries with same key information. How can I pass this list of dictionaries to a Django template ?

listdict = [{'product':'specs','price':'12'}, {'product':'shoes','price':'30'}]

When trying to send this list via views file to template it fails with an error indicating that only dictionaries are allowed.

Here is the code from views file

return render(request, 'recordings/extensionrecording.html',listDict)

Here is the html block-

      <tbody>
                                {%for list in listDict%}
                                {%for elements in list%}
                               
                                
                                
                            <tr>
                             
<td class="body-item fonts-style display-4">{{elements.product}}</td>
<td class="body-item fonts-style display-4">{{elements.price}}</td>
</tr>

Advertisement

Answer

Just pass these as an entry of the dictionary:

return render(request, 'recordings/extensionrecording.html',{'listDict': listDict})

Then in the template, you can render these with:

{%for item in listDict %}
    {{ item.product }}
    {{ item.price }}
{% endfor %}
Advertisement