V
V
Vladislav Koval2020-02-23 16:49:28
Django
Vladislav Koval, 2020-02-23 16:49:28

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

It has a status_choice field which is associated with the issue status model. Task status model:
class Status(models.Model): # Модель статуса для задачи
    status = models.CharField(max_length = 20)

    class Meta:
        verbose_name = 'Статус'
        verbose_name_plural = 'Статусы'

    def __str__(self):
        return self.status


At the moment I have this picture: The
5e5281e5ecf57088062099.png

question is as follows: I need to create 5 blocks for each status, in which tasks will already be filtered by their status, a la like on the trello site:
5e52827c0368f903907477.png

Here is my template:
{% 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 %}


How can you achieve such a result as on the Trello website?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-23
@Realmixer

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 question

Ask a Question

731 491 924 answers to any question