Как сделать счетчик лайков в django - PullRequest
0 голосов
/ 09 июля 2020

Я хочу сделать такой счетчик на моем веб-сайте под моим кодом, кто-нибудь скажет мне, какие изменения я делаю, чтобы сделать, например, счетчик. Любой tellme / ............... .................................................. .................................................. .................................................. ................................................

Моя модель существует как LikeModel:.

Models00.py

class Like(models.Model):
    user = models.ManyToManyField(User, related_name="linkingUser")
    post = models.OneToOneField(Post, on_delete=models.CASCADE)

    # for liking post
    @classmethod
    def like(cls, post, liking_user):
        obj, create  = cls.objects.get_or_create(post = post)
        obj.user.add(liking_user)

    # for disliking post
    @classmethod
    def dislike(cls, post, disliking_user):
        obj, create  = cls.objects.get_or_create(post = post)
        obj.user.remove(disliking_user)

    def __str__(self):
        return str(self.post)

class Post(models.Model):
     user    =models.ForeignKey(User,on_delete=models.CASCADE,related_name='user')
     image   =models.FileField(upload_to='post',blank=True)
     caption = models.CharField(max_length=200,default="")
     views   = models.IntegerField(default=0)
     date    =models.DateTimeField(auto_now_add=True,blank=True, null=True)
     liked    =models.ManyToManyField(User,default=None,blank=True)

     def __str__(self):
         return str(self.user)+'   '+  str(self.date.date())         
     @property
     def num_likes(self):
         return self.liked.all().count()      

views.py

def likePost(request):
    post_id = request.GET.get("likeId", "")
    post = Post.objects.get(pk=post_id)
    user = request.user
    like = Like.objects.filter(post = post, user=user)
    # like,created=Like.objects.get_or_create(user=user,post_id=post_id)
    liked = False

    if like:
          Like.dislike(post, user)
    else:

           liked = True
           Like.like(post, user)

    resp = {
        'liked':liked
    }
    response = json.dumps(resp)
    return HttpResponse(response, content_type = "application/json")

шаблон. html

    <button class="btn btn-light mr-3 like" id="{{ i.id }}">
  
      {% if i in liked_post and i.liked.all %}
          <a href="{% url 'user_homeview:like_dislike_post' %}" style="color:red;" id="likebtn{{ i.id }}"> Liked </a>
      {% else %}
          <a href="{% url 'user_homeview:like_dislike_post' %}" style="color:red;" id="likebtn{{ i.id }}"> Like </a>
      {% endif %}
    </button><br>

  
  <strong>{{i.liked.all.count}}&nbsp;Likes</strong>

например. js

$(".like").click(function (e) {
    var id = this.id; //$(this).attr('id');
    var href = $('.like').find('a').attr('href');
    e.preventDefault(); // don't follow the link

    $.ajax({
        url: href,
        data: {
          'likeId': id
        },
        success: function(response){
          if(response.liked){
            $('#likebtn' + id).html("Liked");
          }
          else{
            $('#likebtn' + id).html("Like");
          }
        }
      })
});
...