Miguel Toledano
Miguel Toledano

Reputation: 407

Django & ajax like button only works in first item

good morning, I just got a problem with my like button, it's only working on the first item and it does not work on the others

This is my views.py

@login_required
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        tweet = get_object_or_404(Tweet, slug=slug)
        if tweet.likes.filter(id=user.id).exists():
            tweet.likes.remove(user)
            message = 'Your disliked this'
        else:
            tweet.likes.add(user)
            message = 'You liked this'
    ctx = {'likes_count': tweet.total_likes, 'message':message}
    return HttpResponse(json.dumps(ctx), content_type='application/json')

When I click in the like button on the first item this works fine but, when I click like button in the other items this not works.

My models.py

class Tweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField('Titulo', max_length=100)
    text = models.CharField(max_length=160)
    slug = models.SlugField(max_length=180)
    likes = models.ManyToManyField(User, related_name='likes')
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    @property
    def total_likes(self):
        return self.likes.count()

and this is my scrip ajax:

<script type="text/javascript">
$("#like-button").click(function(e){
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      alert("This tweet has " + response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});

</script>

My html button:

    <input
    type="button"
    id="like-button"
    name="{{tweet.slug}}"
    value="Like {{tweet.total_likes}}"
    class="btn btn-primary">

Upvotes: 1

Views: 498

Answers (2)

Alasdair
Alasdair

Reputation: 308919

If you have multiple inputs you should use a class, not an id.

<input
type="button"
class="like-button"
name="{{tweet.slug}}"
value="Like {{tweet.total_likes}}"
class="btn btn-primary">

You'll also have to update your ajax:

$(".like-button").click(function(e){

Upvotes: 3

Brandon Miller
Brandon Miller

Reputation: 1584

You have multiple buttons, all with the same id of "like-button"? If that is the case, try deleting the ID since, from what I can see in the code, it isn't being used. ID's should always be completely unique. Having multiple elements with the same ID usually cause issues like this.

Upvotes: 2

Related Questions