Django Template: key, value not possible in for loop

Viewed 12167

Error I get:

Need 2 values to unpack in for loop; got 1.

Here is my view:

class Index(View):
    def get(self, request, slug):
        test = {
            1: {
                'id': 1,
                'slug': 'test-slug-1',
                'name': 'Test Name 1'
            },
            2: {
                'id': 2,
                'slug': 'test-slug-2',
                'name': 'Test Name 2'
            }
        }
        context = {
            'test': test
        }
        return render(request, 'wiki/category/index.html', context)

Here is my template:

{% block content %}
    <div>
        {{ test }}
        <ul>
            {% for key, value in test %}
                <li>
                    <a href="#">{{ key }}: {{ value }}</a>
                </li>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

I also tried the template like:

{% block content %}
    <div>
        {{ test }}
        <ul>
            {% for value in test %}
                <li>
                    <a href="#">{{ value }}: {{ value.name }}</a>
                </li>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

No error then, but {{ value }} shows key (which is fine), but {{ value.name }} shows nothing. While {{ test }} shows my dict.

2 Answers

Loop through the dictionary's items to get the keys and values:

{% for key, value in test.items %}

Not familiar with Django. However, by default, Python iterates over the keys for a dictionary. I am also going to assume you are using Python2. To get the values, you need to do:

{% for value in test.itervalues() %}

If you want both, you need to do:

{% for key, value in test.iteritems() %}

That will give you both the key and the value.

Related