繁体   English   中英

如何在我的列表视图中的每个帖子上运行一个函数并将一个布尔变量传递到我的 html 中?

[英]How do I run a function on each post in my list view and pass a boolean variable into my html?

我的html

{% if post.is_liked %}
    <i class="fa fa-check" aria-hidden="true"></i>
{% else %}
    <i class="fa fa-times" aria-hidden="true"></i>
{% endif %}

我的意见.py

class PostListView(ListView):
    queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31'])
    template_name = 'main/problems.html'
    context_object_name = 'posts'
    ordering = ['-created']

    def get_liked(self):
        post = self.get_object()
        user = get_object_or_404(User, username=post.kwargs.get('username'))
        if post.likes.filter(username=user).exists():
            post.annotate(is_liked=True)
        else:
            post.annotate(is_liked=False)

即使我将两个条件都设置为返回 true,我的 html 也不会读取is_liked为 true。

您的for循环将在您构造类时简单地运行,而且您将简单地定义一个函数(多次),而不是执行该函数。 最后请注意,这应该改变Post的属性,而不仅仅是一个通用对象。

您可以使用以下方法注释查询集:

from django.db.models import Exists, OuterRef
from app.models import Post, Like

class PostListView(ListView):
    model = Post
    template_name = 'main/problems.html'
    context_object_name = 'posts'
    ordering = ['-created']
    def get_queryset(self, *args, **kwargs):
        Post.objects.filter(
            created__range=['2020-03-01', '2020-03-31']
        ).annotate(
            is_liked=Exists(Like.objects.filter(
                user_id=self.request.user.pk, post_id=OuterRef('pk')
            ))
        )

user_idpost_id可能具有不同的名称,具体取决于您构建Like模型的方式。

然后在模板中,您可以检查Post对象的is_liked属性:

{% for post in posts %}
    {% if post.is_liked %}
        …
    {% else %}
        …
    {% endif %}
{% endfor %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM