在Django模板中如何找出request.user是否在与用户关联的对象列表中?

时间:2014-04-06 08:48:19

标签: 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.DateTimeField(default=now)

class CohortMembers(models.Model) :
    cohort = models.ForeignKey(Cohort)
    member = models.ForeignKey(User)
    creation_date = models.DateTimeField(default=now)

因此,您可以看到群组与用户之间存在多对多关系。

在模板中,我正在列出同类群组(简化为了给你提示):

{% for cohort in object_list %}
  <a href="./{{ cohort.cohort_name }}/">{{ cohort.cohort_name }}</a>
  <!-- list all members of the cohort -->
  {% for cohortmember in cohort.cohortmembers_set.all %}
    {% if request.user.username == cohortmember.member.username %}
      <!-- the user is a member of the cohort, provide a delete button -->
      <button>Leave cohort</button>
    {% else %}
      Some other user called {{ cohortmember.member.username }} is a member.
    {% endif %}
  {% endfor %}
{% endfor %}

我需要做的是为用户提供一个按钮,以便加入群组(如果他们还不是会员)。在最原始的python中,你可能会这样做;

# clearly some better python would be to use a django model query, rather
# than iterate over the members, but this encapsulates the basic logic
is_member = False
for cohortmember in cohort.cohortmembers_set.all:
     if request.user == cohortmember.member:
        is_member = True
if is_member :
     # a leave button
else:
     # a join button

我可以在Django模板语言中执行任何操作,还是必须将这样的代码放入View类中?

1 个答案:

答案 0 :(得分:0)

我发现这样做的唯一真正方法是操作CohortView和一些简单的模板编程。

我转过头来问:不要问“这个用户是该群组的成员吗?”但是它成了“这个用户会员名单中的队列吗?”以这种简单的方式。

在CohortListView的get_context_data中如下:

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 %}