问题是,当我在shell中检查它们时,我试图比较两个相同的属性,但条件不完整,我不明白为什么。我的意思是这种情况:{%if c.author = member.name%}
的观点:
cvs = Cv.objects.all()
cv = Cv.objects.filter(author = request.user)
per = Person.objects.all()
gr = Group.objects.filter(members__name=request.user)
for c in cvs:
print c.author
mem = Membership.objects.all()
form = GroupForm()
context = {
'gr': gr,
'per':per,
'mem':mem,
'form': form,
'cvs':cvs,
'cv':cv,
}
return render(request, 'groups.html', context)
models.py:
class Cv(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=25, null = True)
surname = models.CharField(max_length=25, null = True)
address = models.CharField(max_length=100, blank=True)
telephone = models.IntegerField()
birth_date = models.DateField(blank=True, null=True)
email = models.EmailField(max_length=50, null=True)
skills = models.TextField(null=True)
specialization = models.CharField(max_length=30, blank=True, null=True)
interests = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
@property
def age(self):
return int((datetime.datetime.now().date() - self.birth_date).days / 365.25 )
def zapisz(self):
self.save()
def __str__(self):
return self.surname
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')
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)
groups.html:
{% block profile %}
{% for g in gr %}
<div class="jumbotron">
<p><b>GROUP:</b> {{g.name}}</p>
{% for c in cvs %}
{% for member in g.members.all %}
{% if c.author = member.name %}
{{member.name}}
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
{% endblock %}
谢谢你的回答!
答案 0 :(得分:2)
首先,请为变量提供描述性名称。 “c”和“gr”是不可能理解的。
其次,你根本没有比较正确的事情。 c.author
是User的一个实例; member
是Person的实例,member.name
是字符串。将User实例与字符串进行比较将始终失败。
最后,整个事情可怕效率低下 - 而且可能完全没必要。三个嵌套的for循环意味着大量的迭代。如果你能解释一下输出需要什么,那么我们几乎肯定会想出一个更好的方法。
答案 1 :(得分:1)
要在Django模板中测试相等性,您需要使用等于运算符==
,如下所示:
{% if c.author == member.name %}
{{member.name}}
{% endif %}
答案 2 :(得分:0)
您应该将c.name与member.name或c.author.first_name与member.name进行比较。所以这两个变量都是字符串。