几天前开始学习 Django,但现在我被这个问题困住了。
这是一个博客网站,我目前正在使用喜欢/不喜欢功能。
现在,经过身份验证的用户可以根据需要多次喜欢同一个帖子。
我想我的模型有问题。 (或者在我看来可能是它的条件)
我将非常感谢您的帮助和澄清! :)

这是我的模型(Post.py):

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name='author')
    title = models.CharField(max_length=80, verbose_name="Название")
    body = models.TextField(verbose_name="Текст публикации")
    created = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания")
    modified = models.DateTimeField(auto_now=True, verbose_name="Дата обновления")
    description = models.CharField(max_length=400,verbose_name = "Описание")
    reading_time = models.PositiveSmallIntegerField(verbose_name="Время для чтения в минутах")
    likes = models.PositiveIntegerField(default=0)
    dislikes = models.PositiveIntegerField(default=0)
    users_reaction = models.ManyToManyField(User, blank=True, verbose_name='Реакция юзеров', related_name='react')

我的观点(Post.py):
class UserReactionView(View):
    template_name='post.html'

    def get(self, request, *args, **kwargs):
        post_id = self.request.GET.get('post_id')
        post = Post.objects.get(id = post_id)
        like = self.request.GET.get('like')
        dislike = self.request.GET.get('dislike')
        post_user_reactions = Post.objects.filter(user=request.user)
        if like and (request.user not in post_user_reactions.all()):
            post.likes += 1
            post.users_reaction.add(request.user)
            post.save()
        if dislike and (request.user not in post_user_reactions.all()):
            post.dislikes += 1
            post.users_reaction.add(request.user)
            post.save()
        data = {
            'likes': post.likes,
            'dislikes': post.dislikes
        }

        return JsonResponse(data)

和模板中的 jquery 块
{% block jquery %}
<script>
  $(document).ready(function(){
      $('#like').on('click', function(e){
          e.preventDefault()
          var post_id = {{ post.pk }}
          var like = 'like'

          data = {
              post_id: post_id,
              like: like
          }
          $.ajax ({
              type:"GET",
              url:"{% url 'blog:user_reaction'  post.pk%}",
              dataType: 'json',
              data: data,
              success: function(data){
                  $('#liked').html(data.likes)
                  $('#disliked').html(data.dislikes)

              }
          })
      })

  })

     $(document).ready(function(){
           $('#dislike').on('click', function(e){
          e.preventDefault()
          var post_id = {{ post.pk }}
          var dislike = 'dislike'

          data = {
              post_id: post_id,
              dislike: dislike
          }
          $.ajax ({
              type:"GET",
              url:"{% url 'blog:user_reaction' post.pk %}",
              dataType: 'json',
              data: data,
              success: function(data){
                  $('#liked').html(data.likes)
                  $('#disliked').html(data.dislikes)

              }
          })
      })

  })
</script>

 {% endblock %}

最佳答案

您的查询有误:

post_user_reactions = Post.objects.filter(user=request.user)

此查询过滤掉 request.user 创建的所有帖子。

像这样改变它:
post_obj = Post.objects.get(id = post_id)
# Now get all the users that reacted to this post.
post_user_reactions = post_obj.users_reaction.all()

if like and (request.user not in post_user_reactions):
    ...
if dislike and (request.user not in post_user_reactions):
    ...

关于jquery - 如何让用户在 Django 中只喜欢/不喜欢帖子一次?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55296608/

10-12 21:44