I want to print both, keys and values of dictionary which I pass in render to a HTML page in Django

Viewed 122

This loop format in html is only printing the key but not value,I want to print both key and value in html page.

views.py

def predict(request):
    if request.method == "POST":
         dict = {'Name': John, 'Age': 40}
         return render(request,'standalone.html',{'content':dict})
    else:
         return render(request,'test_homepage.html')

satandalone.html

{% for c in content %}
    {{c}}
{% endfor %}
3 Answers

You use .items() to obtain an iterable of 2-tuples.

def predict(request):
    if request.method == "POST":
         data = {'Name': 'John', 'Age': 40}
         return render(request,'standalone.html',{'content': data.items()})
    else:
         return render(request,'test_homepage.html')

In the template, you can then render this with:

{% for k, v in content %}
    {{ k }}: {{ v }}
{% endfor %}

Note: Please do not name a variable dict, it overrides the reference to the dict class. Use for example data.

Try this in your template satandalone.html:

{% for c in content %}
    {{ c.name }}
    {{ c.age }}
{% endfor %}

Try this. It might help you.

{% for key, value in content.items %}
    {{ key }}: {{ value }}
{% endfor %}

Related