我怎样才能设置我的会员资格,而不是全部用于for-loop?
template.html:
{% for g in gr %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Groups name:</b> {{g.name}}</p><br>
{% for membership in g.membership_set.all %}
<p><b>Member:</b> {{ membership.person }} - {{ membership.role }}</p>
{% endfor %}
<br>
<span class="desc2">Groups description:</span>
<p id="desc">{{g.description}}</p><br>
{% for membership in g.membership_set.all %}
{% if membership.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif membership.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endfor %}
</form>
<br><br>
<p></p>
</div>
</div>
{% endfor %}
models.py:
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
description = models.TextField(max_length=350)
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
leader = models.BooleanField(default=False)
group = models.ForeignKey(Group)
role = models.CharField(max_length=50)
我的按钮很多,因为我在某些群组中拥有用户。 我想只显示1个按钮,我需要精确的ForLoop只为我在这个组中的会员资格。我怎么能这样做?
答案 0 :(得分:0)
我认为只使用标准模板代码就可以做到这一点。您需要通过过滤会员资格来获取Membership
对象:
membership = my_person.membership_set.get(group=my_group)
要在模板中执行此操作,您必须编写适用于my_person
对象的own template filter并将my_group
对象作为参数。然后,过滤器可以应用上述查询并返回成员资格对象。
{% with membership=my_person|get_group_membership:g %}
{% if membership.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif membership.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endwith %}