David Louda
David Louda

Reputation: 577

How to iterate over a queryset in django template?

I am aware that this is very likely a duplicate but solutions provided in alike questions did not help.

This is at first glance very straightforward issue, it should work by all means but for some reason, it does not.

In a Django template, I am filtering a queryset of records based on the current user. Then I loop through it and want to display each result separately. Nothing complicated. The code goes:

{% if user.is_authenticated %}
    {% if user.quick_links.all %}
        {{ user.quick_links.all }}
        <h2>Moje rychlé přístupy:</h2>
        {% for link in user.quick_liks.all %}
            <div class="col-md-2">
            <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }</button></a>
            </div>
        {% endfor %}
    {% endif %}
{% endif %}

the {{ user.quick_links.all }} displays

<QuerySet [<UserQuickAccessLink: Link uživatele [email protected]: Google>, <UserQuickAccessLink: Link uživatele [email protected]: Coding Music>]>

but then the program never enters the for loop even though the iterable is clearly there.

{% for link in user.quick_liks.all %}
    <div class="col-md-2">
    <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }} </button></a>
    </div>
{% endfor %}

The above is never executed. What is the trick here?

Upvotes: 0

Views: 727

Answers (1)

Innaam Faizal
Innaam Faizal

Reputation: 26

If that is your actual code, in your for loop you have a typo;

It's supposed to be

{% for link in user.quick_links.all %}

and not

{% for link in user.quick_liks.all %}

Upvotes: 1

Related Questions