Как правильно сделать оператор if в html

Я должен написать оператор if в шаблоне detail.html, который гласит "если в проекте есть задачи", вывести таблицу, иначе вывести "задач в проекте нет". Я пробовал

{% if task in project %}
{% if task in projects_list %}
{% if tasks in project %}

"выводит таблицу"

{% else %}
<p>no tasks for this project</p>
{% endif %}

вот моя модель задачи

class Task(models.Model):
    name = models.CharField(max_length=200)
    start_date = models.DateTimeField()
    due_date = models.DateTimeField()
    is_completed = models.BooleanField(default=False)
    project = models.ForeignKey(
        "projects.Project",
        related_name="tasks",
        on_delete=models.CASCADE,
    )
    assignee = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        related_name="tasks",
        on_delete=models.SET_NULL,
    )

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("show_my_tasks")

здесь представлен вид для проектов

class ProjectListView(LoginRequiredMixin, ListView):
    model = Project
    template_name = "projects/list.html"
    context_object_name = "projects_list"

Если проект - это список, то вам, вероятно, нужны:

{% if project|length > 0 %}

Похожий вопрос Проверить, не пуст ли массив в Jinja2

Если я правильно понимаю, вы хотите проверить, имеет ли project связь с task. Если это так, вы можете обратиться к атрибуту project на Task model, используя related_name, который является tasks в шаблоне. Например:

# using project.tasks to check for an existing relationship with project and task; 
# calling the count method as well to count how many tasks are connected to a project within the loop.
{% if project.tasks.count > 0 %}
     # Displaying the table in here with the project's task info...
{% else %}
     <p> no tasks for this project </p>
{% endif %}

В идеале, ваш for loop будет выглядеть примерно так:

{% for project in projects_list %}
     ...

     {% if project.tasks.count > 0 %}
          # Displaying the table in here with the project's task info...
     {% else %}
          <p> no tasks for this project </p>
     {% endif %}

     ...
{% endfor %}

Это должно сработать.

Частичный ответ, слишком длинный, чтобы добавить его в качестве комментария. Часто не нужно обрабатывать случай пустого списка или множества вне цикла for. Вместо этого:

{% for task in project.tasks %}
   {% if forloop.first %}
      <table>  ... and table header
   {% endif %}

    <tr> 
        ... stuff involving display of {{task.field}}s
    </tr>

   {% if forloop.last %}
     </table> ... and any other table footer stuff
   {% endif %}

   {% empty %} ... optional
      stuff to show if there are no tasks

 {% endfor %}
Вернуться на верх