Answer the question
In order to leave comments, you need to log in
Filter by model objects in templates?
Hello. I am making a clone of trello (a board with puzzles), the following problem has appeared.
There is a task model:
class Task(models.Model):
article = models.TextField(null=True, blank=True)
status_choice = models.ForeignKey(Status, on_delete = models.CASCADE, default = 1)
class Meta:
verbose_name = 'Задача'
verbose_name_plural = 'Задачи'
def __str__(self):
return self.article
class Status(models.Model): # Модель статуса для задачи
status = models.CharField(max_length = 20)
class Meta:
verbose_name = 'Статус'
verbose_name_plural = 'Статусы'
def __str__(self):
return self.status
{% extends 'base.html' %}
{% block content %}
<style> .card{
width:250px;
margin: 5px;
padding: 5px;
}</style>
<div class="card-group d-flex flex-wrap">
{% for i in tasks %}
<div class="col-sm-3">
<div class="card">
<div class="card-block">
<h4 class="card-title">{{ i.status_choice }}</h4>
<p class="card-text">{{ i.article }}</p>
<a href="#" class="btn btn-primary">переместить</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Answer the question
In order to leave comments, you need to log in
First, filtering is business logic. And business logic has no place in templates. Remove this logic in the model, the service layer, or at least in the controllers.
Secondly, in the template, you simply loop through all the tasks. While according to your description, you should loop through the statuses, and inside it a nested loop through the tasks of each status:
{% for status in status_list %}
<h1>{{ status }}</h1>
{% for task in status.tasks.all %}
<h2>{{ task }}</h1>
{% endfor %}
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question