Django使用queryset对象的属性



我为我的页面创建了评论/消息区域。然后创建like buttons对他们也一样。当用户进入页面时,我想显示默认的喜欢按钮(喜欢或不喜欢)。如果用户在like列表中,我想显示他不像但是我想显示Like按钮,如果它不在列表中,也就是说,如果它还没有被喜欢。

视图:

def detail_post(request,_detail):
postDetail =  UserPosts.objects.get(pk = _detail) #This is post
messages = UserMessages.objects.all().filter(post_id =postDetail.id) #This is comment of post
# I tried this but iit is not works
for x in messages:
total = x.like_message.all()
print(total)    
context= {
"detail":postDetail,
"messages":messages,
}

模板:

{% for message in messages %}
{% if message.username_id == request.user.id %}
<button class="btn btn-primary btn-sm" title="You can't like your message" disabled >Like</button>
{% else %}
<button class="btn btn-primary btn-sm text-white btn-like {{ message.id }} " type="submit" name="usermessages_id"
value="{{ message.id }}" id="{{ message.id }}"> Like </button>
{% endif %}
{% endfor %}

下面是我在Views文件中编写的for循环的输出:

<QuerySet [<User: vahandag>]>
<QuerySet [<User: vahandag>, <User: GladyaTH0R>, <User: user2>, <User: user3>, <User: vahandag1905>]>
<QuerySet []>
<QuerySet []>
<QuerySet [<User: vahandag1905>]>
<QuerySet [<User: vahandag1905>]>
<QuerySet [<User: vahandag>]>

我想要这个:

{% if message.username in message.like_message.all() %}
<button> Unlike </button>
{% else %}
<button> Like </button>
{% endif %}

有人有什么想法吗?

试试这个

{% if message.username in message.like_message.all %}
<button> Unlike </button>
{% else %}
<button> Like </button>
{% endif %}

你不必在模板引擎

中以'()'结束方法

try this

def detail_post(request,_detail):
postDetail =  UserPosts.objects.get(pk = _detail) 
messages = UserMessages.objects.all().filter(post_id=postDetail.id).values() 
#This is comment of post
# I tried this but iit is not works
for x in messages:
total = x.like_message.all()
print(total)    
context= {
"detail":postDetail,
"messages":messages,
}

相关内容

  • 没有找到相关文章

最新更新