How to display array elements in python

Question:

I’m trying to browse this array and display it on my django project but it doesn’t work.

Views.py

def(request):
  
  {"product":[
    {
      "name":"sogi",
      "desc":"solo"
    },
    {
      "name":"molo",
      "desc":"kanta"
    },
  ]
 }
   context={"tab":"product"}
   return render(request,'api/myapi.html',context)

myapi.html

  {% for pro in tab %}
    {{pro.name}}
  {% endfor %}
Asked By: Macba

||

Answers:

You have to change your context creation:

def(request):
    tab = {"product": [...]}
    products = tab["products"]
    context = {"products": products}
    return render(request, "api/myapi.html", context)

And change usage in your template:

{% for product in products %}
    {% for key, value in product.items %}
        {{ key }}: {{ value }}<br>
    {% endfor %}
{% endfor %}
Answered By: NixonSparrow
def yourFunName(request):
    dict = {
          "product":[
             {
              "name":"sogi",
              "desc":"solo"
             },
             {
              "name":"molo",
              "desc":"kanta"
             },
                    ]
           }
 
    tab = dict['product']
    return render(request, 'api/myapi.html', {"tab":tab)

in html do this:

{% for pro in tab %}
    {{ pro.name }}
    {{ pro.desc }}
{% endfor %}
Answered By: Hemal Patel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.