如何在模板中显示当前用户在项目中的角色?

时间:2017-04-26 11:46:16

标签: python html django python-3.x django-1.10

有人可以说我错了吗?

我有Project型号。每个项目都有成员。我有project_detail页面,我想要显示当前用户的用户名和他在项目中的角色。在模板中知道它只显示当前用户的用户名,但不显示他在项目中的角色。

models.py:

class Project(models.Model):
    members = models.ManyToManyField(User, through='Member', help_text=_('Members'))

ROLE_CHOICES = (
    ('manager', _('Manager')),
    ('developer', _('Developer')),
    ('business_analyst', _('Business Analyst')),
    ('system_analyst', _('System Analyst')),
)

class Member(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES)

views.py:

def project_detail(request, project_code):
    project = get_object_or_404(Project, pk=project_code, status='open')
    context = {'project': project,}
    return render(request, 'project/project_detail.html', context)

project_detail.html:

<span class="nav-link active navbar-text">
   {{ user.get_username }}:

   {% for member in project.member_set.all %}
       {% if member.user == user.get_username %}
          {{ member.get_role_display }}
       {% endif %}
    {% endfor %}
</span>

1 个答案:

答案 0 :(得分:2)

为什么要将用户与get_username的结果进行比较?这可能会返回一个用户名字符串,但用户就是用户。这可行:

{% if member.user == user %}
  {{ member.get_role_display }}
{% endif %}

但不要这样做。循环遍历所有项目成员并为每个成员获取用户是非常低效的。而是在视图中执行单个查询:

member = project.member_set.get(user=request.user)
context = {'project': project, 'role': member.get_role_display()}