-1

I create a dictionary, and pass it to my Django template:

my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
t = get_template('my_site.html')
html = t.render(my_dict)
print(html)
return HttpResponse(html)

My Django template looks like this:

<html>
<body>
Out of Dictionary <div>
    {% for key in my_dict %}
    <span>{{ key }}</span>
    {% endfor %} 
</div>
After dictionary    
</body>
</html>

My output in the browser looks like this: Out of Dictionary After dictionary

The HTML looks like this:

<html>
<body>
Out of Dictionary <div>

</div>
After dictionary
</body>
</html>

I have also tried the following to get the dict to be recognized:

{% for key in my_dict %}
{% for key in my_dict.items %}
{% for key, value in my_dict.items %}
{% for (key, value) in my_dict.items %}
Jeanne Lane
  • 495
  • 1
  • 9
  • 26

2 Answers2

1

First you need to create a Context object and pass it in to the render function. See this example from the documentation

Secondly, for your code to work as I think you are intending.. you actually need to add another layer on top of what you have so you can reference my_dict in your template

t.render(Context({'my_dict': {'boo': {'id':'42'}, 'hi': {'id':'42'}}}))
Max Friederichs
  • 569
  • 3
  • 13
  • I'm using Django 2.0.2. After Django 1.11 you get the error "TypeError context must be a dict rather than Context." if you pass a Context to render. – Jeanne Lane Feb 22 '18 at 22:34
  • 1
    In that case.. you should only need `t.render({'my_dict': {'boo': {'id':'42'}, 'hi': {'id':'42'}}})` – Max Friederichs Feb 22 '18 at 22:45
1
my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
t = get_template('my_site.html')
html = t.render(my_dict)

Your context has two keys, boo and hi. You can access them in the template as follows:

{{ boo }}, {{ hi }}

If you want to use mydict in the template, you would nest that dictionary in the context dictionary:

my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
context = {'my_dict': my_dict}
t = get_template('my_site.html')
html = t.render(context)

In the template you can then do:

{{ my_dict }}

or

{% for key, value in mydict.items %}
  {{ key }}: {{ value }}
{% endfor %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Thank you! I put "print(self.nodelist)" in django.template.base.Template.init, and it printed the nodes it was expecting. That showed me your nesting of my_dict was right. I also put print(context) under django.template.backends.django.Template.render, and that showed me the context was formed. – Jeanne Lane Feb 22 '18 at 23:55