问题
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 want now is that I print a subset of the objects, something like:
{% for subObject in mainObject.subobjects.filter(someField=someValue) %}
So far I have searched solutions about the error I get:
Could not parse the remainder: '(someField=someValue)'
but did not find a solution about how the line should be different when a filter is used. I want to tweak just the template.html
file, thus I don't want to make the change on views.py
file (where everything supposedly would work nicely).
How to achieve this?
回答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:
def my_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.
来源:https://stackoverflow.com/questions/22621645/cannot-use-filter-inside-django-template-html