0

你好,我有一个帖子模型,它有一个 like(m2m) 和 user(forgeinkey) 模型字段,我试图检查 request.user 是否喜欢这个帖子,如果有,我应该给他们一个红色的心形按钮,否则是一个蓝色应该显示心脏,现在因为有多个帖子和喜欢,我循环遍历每个喜欢的对象以检查 request.user 是否喜欢它。不幸的是,由于某种原因,我无法实现一个好的逻辑,我看到每个用户都喜欢按钮。一些帮助将不胜感激。

这是我的模型:

class post(models.Model):
    user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE)
    caption = models.CharField(max_length=100)
    image = models.FileField(upload_to='images/', null=True, blank=True)
    video = models.FileField(upload_to='videos/', null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    like = models.ManyToManyField(User, null=True, blank=True, default='')

风景:

@login_required
def usersfeed(request):
    users = User.objects.all()
    posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created')
    comments = Comment.objects.all()
    status_form = StatusForm(request.POST)
    friend_requests = FriendRequest.objects.filter(to_user=request.user)
    friends = request.user.profile.friend.all()
    for i in posts:
        likes = i.like.all()
        print(likes)
        for like in likes:
            if like.username == request.user.username:
                if request.user:
                    Hasliked = True
                    print('liked')
                else:
                    Hasnotliked = True
                    print('not liked')
    context = {
        'Post':posts,
        'User':users,
        'form':PostForm(),
        'Profile':profile,
        'Form':CommentForm(),
        'Comment':comments,
        'Status':status_form,
        'fr':friend_requests,
        'friend':friends,
        'Hasliked':Hasliked,
        'Hasnotliked':Hasnotliked,
    }
    return render(request, 'social_media/feed.html', context=context)

类似计数器的 ajax 视图:

@login_required
def like_post(request):
    Post = get_object_or_404(post, id=request.GET.get('post_id'))
    cssClass = 'colorRed'
    if Post.like.filter(id=request.user.id).exists():
        Post.like.remove(request.user)
    else:
        Post.like.add(request.user)
    count = Post.like.count()
    users = Post.like.all() 
    user = []
    for i in users:
        user.append((i.username))
    response = {
        'count':count,
        'users':user,
        'cssClass':cssClass,
    }
    return JsonResponse(response)

html代码:

{% for i in Post %}
<form action="{% url 'like_post' %}" class='like-submit' data-catid="{{ i.id }}" method="GET">
    <div class="like">
            {% if Hasliked == True %}
                <button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
                    <i class="fas fa-heart"></i>
                </button>
            {% endif %}
            {% if Hasnotliked == True %}
                <button id="likeBtn{{ i.id }}" class="likeClassBtn">
                    <i class="fas fa-heart"></i>
                </button>                      
            {% endif %}
            <div class="show_likes">
            <span id="likes_count{{ i.id }}">{{ i.total_likes }}</span>
            <div class="username_liked">
                <div id="user-likes{{ i.id }}" class="user-likes">
                    {% for p in i.like.all %}
                    {{ p.username }}
                    {% endfor %}
                </div>
            </div>
            </div>
    </div>
</form>
{% endfor %}

<script>
    $(document).ready(function () {
            $(".like-submit").submit(function (event) {
                event.preventDefault()
                const url = $(this).attr('action');
                const catid = $(this).attr("data-catid");
                $.ajax({
                        type: "GET",
                        url: url,
                        data: {
                            post_id: catid,
                        },
                        success: function (data) {
                            $('#likes_count' + catid).html(data.count)
                            if ($('#user-likes' + catid).html()){
                                $('#user-likes' + catid).html(data.users + ' ')
                                $('#likeBtn' + catid).toggleClass(data.cssClass)
                            }
                        }
                });
            });
    });
</script>
4

1 回答 1

1

您需要在该用户的帖子记录中存储 hasLiked/hasNotLiked。上面的代码意味着所有帖子要么被喜欢,要么被不喜欢。您还需要重新考虑加载上下文的方式 - 当前代码效率极低。我建议将 Hasliked 和 Hasnotliked 上下文条目替换为 id 数组,其中每个条目都包含当前用户喜欢/不喜欢的帖子的 id。然后在模板中做检查:

{% if i.id in Hasliked %}   
  <button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
    <i class="fas fa-heart"></i>   
  </button> 
{% endif %} 
{% if i.id in Hasnotliked %}   
  <button id="likeBtn{{ i.id }}" class="likeClassBtn">
    <i class="fas fa-heart"></i>   
  </button>
{% endif %}

hasliked, disliked 可以使用您当前的设置加载:

    friends = request.user.profile.friend.all()
    for i in posts:
        likes = i.like.all()
        print(likes)
        for like in likes:
            if like.username == request.user.username:
                if request.user:
                    Hasliked.append(i.id)
                    print('liked')
                else:
                    Hasnotliked.append(i.id)
                    print('not liked')

这将是非常低效的,最好的方法是直接查询数据库,并简单地返回 id:

l_likedPosts = PostActions.objects.filter(user_id=l_currUser, like
=True)
.values_list('post_id',flat=True) Hasliked = list(l_likedPosts)

上面的代码假定您有一个表 PostActions,其中至少包含 user_id、post_id 和喜欢/不喜欢的状态。这通常是多对多字段在幕后为您所做的,但在更复杂的数据模型中使用它需要太多的自由。

于 2021-05-29T09:54:04.717 回答