0

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 %}
3
  • 1
    you seem to be iterating the string "product" instead of the dictionary Commented Sep 13, 2022 at 8:47
  • def(request): tab = {"product":[ { "name":"sogi", "desc":"solo" }, { "name":"molo", "desc":"kanta" }, ] } context={"tab":tab} return render(request,'api/myapi.html',context) {% for pro in tab['product'] %} {{pro.name}} {% endfor %} Commented Sep 13, 2022 at 8:50
  • i have this error : TemplateSyntaxError at /api/ Could not parse the remainder: '['product']' from 'tab['product']' Commented Sep 13, 2022 at 9:00

1 Answer 1

1

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 %}
Sign up to request clarification or add additional context in comments.

4 Comments

when I do {{ pro.name}} it doesn't show up ?
I've edited a bit my answer. Can you share what {{ pro }} returns to template?
Using your last answer I have : TypeError at /api/ string indices must be integers ! {% for pro in products %} {{ pro.name }} {{ pro.desc }} {% endfor %}
@Macba changed answer again, check it again. It's not that simple to retrieve dictionaries in templates after all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.