Reputation: 110203
I have the following code, where I get all problem notes.
{% for n in task.task_notes.all %}
{% if n.is_problem %}
<li>{{ n }}</li>
{% endif %}
{% endfor %}
How would I only get the first problem note? Is there a way to do that in the template?
Upvotes: 1
Views: 1289
Reputation: 473873
Assuming you need all of the tasks in the template somewhere else.
You can make a reusable custom filter (take a look at first
filter implementation btw):
@register.filter(is_safe=False)
def first_problem(value):
return next(x for x in value if x.is_problem)
Then, use it in the template this way:
{% with task.task_notes.all|first_problem as problem %}
<li>{{ problem }}</li>
{% endwith %}
Hope that helps.
Upvotes: 2
Reputation: 103
use this code in the loop:
{% if forloop.counter == 1 %}{{ n }}{% endif %}
Upvotes: 0
Reputation: 6255
In the view:
context["problem_tasks"] = Task.objects.filter(is_problem=True)
# render template with the context
In the template:
{{ problem_tasks|first }}
first
template filter reference.
Would be even better, if you dont need the other problem tasks at all (from 2nd to last):
context["first_problem_task"] = Task.objects.filter(is_problem=True)[0]
# render template with the context
Template:
{{ first_problem_task }}
Upvotes: 4