Skip to content Skip to sidebar Skip to footer

Cannot Use Filter Inside Django Template Html

I have an issue on my Django project. I have a situation as follows: {% for subObject in mainObject.subObjects.all %} This works nice, every subObject gets iterated nicely. What I

Solution 1:

Following @Yuji'Tomira'Tomita's comment..

Don't put too much logic into the template, quote from django docs:

Philosophy

If you have a background in programming, or if you’re used to languages which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.

Better define the queryset in the view and pass to the template:

view:

defmy_view(request):
    ...
    my_objects = mainObject.subobjects.filter(someField=someValue)
    return render(request, 'mytemplate.html', {'my_objects': my_objects})

template:

{% for subObject in my_objects %}
    ...
{% endfor %}

Hope that helps.

Post a Comment for "Cannot Use Filter Inside Django Template Html"