Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 930
Chad Crowe Avatar asked Dec 13 '25 17:12

Chad Crowe


1 Answers

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 %}
like image 121
Daniel Roseman Avatar answered Dec 16 '25 23:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!