[英]How do properly make an if statement in html
Im supposed to write an if statement in a detail.html template that states "if project has tasks" display a table otherwise display "no tasks in project. I've tried我应该在 detail.html 模板中编写一个 if 语句,说明“如果项目有任务”显示一个表格,否则显示“项目中没有任务。我试过了
{% if task in project %}
{% if task in projects_list %}
{% if tasks in project %}
"displays table" “显示表”
{% else %}
<p>no tasks for this project</p>
{% endif %}
here is my task model这是我的任务模型
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")
here is the view for projects这是项目的视图
class ProjectListView(LoginRequiredMixin, ListView):
model = Project
template_name = "projects/list.html"
context_object_name = "projects_list"
If project is a list you probably want:如果项目是您可能想要的列表:
{% if project|length > 0 %}
Similar question Check if an array is not empty in Jinja2类似问题检查 Jinja2 中的数组是否为空
If I'm understanding correctly, you want to check if a project
has any relationship with a task
.如果我理解正确,您想检查
project
是否与task
有任何关系。 If this is so, you can refer to the project
attribute on the Task
model
by using the related_name
which is tasks
in the template.如果是这样,您可以使用
related_name
中的tasks
相关名称来引用Task
model
上的project
属性。 For example:例如:
# 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 %}
Ideally, your for loop
would look something like:理想情况下,您的
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 %}
That should work.那应该行得通。
Partial answer, too long to add as a comment.部分答案,太长,无法添加为评论。 You often don't need to handle the case of an empty list or set outside of the for loop.
您通常不需要处理空列表或设置在 for 循环之外的情况。 Instead:
反而:
{% 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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.