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
{% 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"
CodePudding user response:
If project is a list you probably want:
{% if project|length > 0 %}
Similar question Check if an array is not empty in Jinja2
CodePudding user response:
If I'm understanding correctly, you want to check if a project
has any relationship with a 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. 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 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.
CodePudding user response:
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. 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 %}