1👍
✅
{% for task in tasks %}
{% for comment in task.comment_set.all|slice:"5" %}
{{ comment }}
{% endfor %}
{% endfor %}
1👍
You don’t. You should not do “real work” in a template, this breaks the MVC pattern.
Do the real work in the view, and pass the data to the template (using the context dictionary).
def handle_comments(request):
tasks = Task.objects.all()
comments = {}
for task in tasks:
comments[task] = task.comment_set.all()[:5]
return render_to_response('commenting.html', {'comments': comments})
You can then iterate over the comments in your template:
{% for task, task_comments in comments.items %}{{ task }}{% endfor %}
- [Answered ]-Django setting.py error
- [Answered ]-Django: changing model's schema (replace CharField with ImageField)
- [Answered ]-Django Choice field best practice in web services
- [Answered ]-How can I prevent duplicate usernames, given that they are case sensitive by default?
- [Answered ]-Django poplulate html form
Source:stackexchange.com