[Fixed]-Django templates: Access value list from dictionary

1👍

First, do not use the keyword list as a variable name. It is a reserved word in Python. Change it to some other name. Second, based on this line of code, you are passing a list into your context. You also need to remove the json.dumps method as this will load a stringified version of your list into your context variable.

context = RequestContext(request,{'appuser':'admin','result':json.dumps(list)})

This means that in your template code, you must iterate over your list first, before you iterate over your dictionary like so. I just added the <br> tags for readability.

{% for x in result %}
    {% for key,value in x.items %}
        {{key}}<br>
        {{value}}<br>
    {% endfor %}
{% endfor %}

If you want to stick with your current template code, you will have to pass a dictionary but use the .items method like so:

{% for key,value in result.items %}
    {{key}}<br>
    {{value}}<br>
{% endfor %}

0👍

You can access the values in Djangos template language using dictionary.items

Try the following:

{% for key, value in result.items %}
    {{ key }} 
    {{ value }}
{% endfor %}
👤Ryan

Leave a comment