Python 在Django模板中,如何确定request.user是否位于与该用户关联的对象列表中?

Python 在Django模板中,如何确定request.user是否位于与该用户关联的对象列表中?,python,django,django-templates,Python,Django,Django Templates,我有一个Django模型,看起来像这样 from django.contrib.auth.models import User class Cohort(models.Model) : cohort_name = models.CharField(max_length=64, primary_key=True) cohort_description = models.TextField(null=False) creation_date = models.DateTime

我有一个Django模型,看起来像这样

from django.contrib.auth.models import User
class Cohort(models.Model) :
    cohort_name = models.CharField(max_length=64, primary_key=True)
    cohort_description = models.TextField(null=False)
    creation_date = models.DateTimeField(default=now)

class CohortMembers(models.Model) :
    cohort = models.ForeignKey(Cohort)
    member = models.ForeignKey(User)
    creation_date = models.DateTimeField(default=now)
所以你可以看到在群组和用户之间有一种多对多的关系

在一个模板中,我列出了这样的队列(简化为给你一个想法):


我可以用Django模板语言来做这些吗?或者我必须把这样的代码放到View类中吗?

我找到的唯一真正的方法是操作CohortView和一点简单的模板编程相结合

我把问题转过来:不是问“这个用户是那个群组的成员吗?”而是用这种简单的方式把它变成“这个群组在用户的成员列表中吗?”

在CohortListView的get_context_数据中,如下所示:

def get_context_data(self, **kwargs) :
    context = super(CohortListView, self).get_context_data(**kwargs)
    memberships = CohortMembers.objects.filter(member=self.request.user)
    cohorts = []
    for membership in memberships:
        cohorts.append(membership.cohort)
    context['memberships'] = cohorts
    return context
注意,我放弃了多对多对象,只在上下文中直接存储用户所属的群组列表

然后,在模板中:

{% for cohort in object_list %}
  {% if cohort in memberships %}
    <!-- leave button -->
  {% else %}
    <!-- join button -->
  {% endif %}
{% endfor %}
{%用于对象列表%中的队列]
{%if成员资格中的队列%}
{%else%}
{%endif%}
{%endfor%}
def get_context_data(self, **kwargs) :
    context = super(CohortListView, self).get_context_data(**kwargs)
    memberships = CohortMembers.objects.filter(member=self.request.user)
    cohorts = []
    for membership in memberships:
        cohorts.append(membership.cohort)
    context['memberships'] = cohorts
    return context
{% for cohort in object_list %}
  {% if cohort in memberships %}
    <!-- leave button -->
  {% else %}
    <!-- join button -->
  {% endif %}
{% endfor %}