【发布时间】:2021-02-26 10:57:00
【问题描述】:
我正在尝试制作一个赞按钮。一切正常,除了我无法检查(在模板内)用户是否已经喜欢某些东西。换句话说,我无法检查数据库中的现有行。
我正在为模板尝试这个: 如果用户喜欢这篇文章。那个帖子显示的是一颗充满的心,否则它只显示一个心脏轮廓
{% for post in posts %}
{% if post in likelist %}
<i class="fa fa-heart like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"></i>
{% else %}
<i class="fa fa-heart-o like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;">
</i>
{% endif %}
{% endfor %}
但 if 语句总是给出 False,即使用户实际上喜欢该帖子。
这是模型:
class Likelist(models.Model):
user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='liker')
likes = models.ForeignKey('Posts', on_delete=models.CASCADE, related_name='likes')
def __str__(self):
return f"{self.user} likes {self.likes}"
我正在通过渲染传递views.py中的上下文
return render(request, "network/profile.html", {
#[...]some other contexts
"posts": Posts.objects.filter(user=user_id).order_by('-timestamp'),
"likelist": Likelist.objects.filter(user=request.user),
})
如果我尝试在 HTML 标记({{likelist}} 或 {{posts}})中打印它,则会出现查询集,因此上下文可以正常传递。 我不知道为什么条件不检查数据库中元素的存在
【问题讨论】:
-
likelist是一组Likelist对象,post是Post对象,所以Post对象永远不能在likelist中。
标签: python html django templates model