Chad Crowe
Chad Crowe

Reputation: 1338

Iterate through Django queryset within template

I have created a custom filter that returns a queryset of objects.

in: templatetags

@register.filter(name = 'create_html_for_deleting_notes')
    def create_html_for_deleting_notes(task_pk):
    corresponding_notes = Note.objects.filter(its_task = Task.objects.filter(pk = task_pk))
    return(corresponding_notes)

in template:

{% for corresponding_task in corresponding_tasks %}
    <h5>{{ corresponding_task | create_html_for_deleting_notes }}<h5/>
{% endfor %}

This works in printing out my queryset. I would like to iterate through that queryset, something like:

in template:

{% for corresponding_task in corresponding_tasks %}
    {% for note in corresponding_task | create_html_for_deleting_notes %}
         {{ note }}
    {% endfor %}
{% endfor %}

But this gives me the error 'for statements should use the format "for x in y"'

Thank you for the help!

Upvotes: 3

Views: 5344

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You need to remove the spaces around the filter | character.

However, I don't think you need the filter at all. You didn't post your model, but it seems like you have a foreignkey relationship between Task and Note, so you should just use the reverse accessor:

{% for corresponding_task in corresponding_tasks %}
    {% for note in corresponding_task.note_set.all %}
         {{ note }}
    {% endfor %}
{% endfor %}

Upvotes: 3

Related Questions