Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template: key, value not possible in for loop

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.

like image 478
bonblow Avatar asked Sep 26 '17 23:09

bonblow


1 Answers

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

{% for key, value in test.items %}
like image 179
Alasdair Avatar answered Nov 14 '22 05:11

Alasdair