Home > Enterprise >  How to display array elements in python
How to display array elements in python

Time:09-13

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 %}

CodePudding user response:

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 %}

CodePudding user response:

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 %}
  • Related