在模板中显示用户团队

时间:2019-05-22 22:02:37

标签: python django django-templates

我有3个模型-项目模型,团队模型和CustomUser模型。我试图在用户的详细信息页面上显示用户所属的团队列表,并在项目的详细信息页面上显示属于项目团队的用户列表,但我处于停滞状态。

# project/users/models.py

class CustomUser(AbstractUser):
    name = models.CharField(max_length=255)

    # Relationship Fields
    team = models.ManyToManyField(
        'users.Team',
        related_name="teams",
    )

class Team(models.Model):
    # Relationship Fields
    project = models.OneToOneField(
        'projects.Project',
        on_delete=models.CASCADE, related_name="projects", 
    )
# project/projects/models.py

class Project(models.Model):
    name = models.CharField(max_length=255)

project / projects / templates / projects / project_detail.html

{% for user in project.team.user.all %}
    {{ user.name }}
{% endfor %}

我尝试了上述方法的变体,例如

{% for user in users.teams.projects.all %}
    {{ user.name }}
{% endfor %}

但是我似乎什么也没显示。我认为我在做一些简单的错误-我已经阅读了有关显示ManyToManyFields的文档,但我很茫然!有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

我不确定,但我认为在这种情况下会错过使用related_name:

class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
    'projects.Project',
    on_delete=models.CASCADE, related_name="projects", 
)

这意味着在类Project的一个对象中将具有一个属性,名称为project,将引用团队。我相信你想要

class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
    'projects.Project',
    on_delete=models.CASCADE, related_name="team", 
)

因此您将可以致电project.team。

更改代码:

# project/users/models.py

class CustomUser(AbstractUser):
    name = models.CharField(max_length=255)

    # Relationship Fields
    team = models.ManyToManyField(
        'users.Team',
        related_name="customers",
    )

class Team(models.Model):
    # Relationship Fields
    project = models.OneToOneField(
        'projects.Project',
        on_delete=models.CASCADE, related_name="team", 
    )

class Project(models.Model):
    name = models.CharField(max_length=255)

因此,现在您可以在模板中:

{% for user in project.team.customers.all %}
    {{ user.name }}
{% endfor %}