Ronit Shrivastava
Ronit Shrivastava

Reputation: 41

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

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

Upvotes: 2

Views: 449

Answers (3)

Md Fantacher Islam
Md Fantacher Islam

Reputation: 82

Try this. It might help you.

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

Upvotes: 0

math-s
math-s

Reputation: 145

Try this in your template satandalone.html:

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

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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.

Upvotes: 4

Related Questions