如何使用户只能在Django中点赞/不喜欢一次?

时间:2019-03-22 09:33:12

标签: jquery json ajax django python-3.x

几天前开始学习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 %}

1 个答案:

答案 0 :(得分:1)

您的查询有误:

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):
    ...