Liel
Liel

Reputation: 1

how to make a like wise button django

I have an Article model which has a votes IntegerField, now I want to make it so that when the user clicks it the votes go up by one and that I managed to make, however, how can I make so next time he clicks it goes down by one. views.py:

@login_required
def vote(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    vote, created = Vote.objects.get_or_create(article=article, user=request.user)
    if created:
        article.votes += 1
        article.save()
        return JsonResponse(data = {"vote": "Voted! Thank you for the vote."})
    return JsonResponse(data = {"vote": "You already voted for this article."})

I have a Vote model which has a user and article foreignkey. The button which "likes" article with ajax:

<button id="vote" class="button">vote</button>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
      var voted = false;
        $("#vote").click(function (e) {
          if (!voted) {
            e.preventDefault()
            var upvotes = $("#total_votes").html()
            voted = true;
            var updatedUpVotes = parseInt(upvotes) + 1
            $("#total_votes").html(updatedUpVotes)
            $.ajax({
              url: 'vote/',
              method: "GET",
              data: {},
              success: function (data) {
                console.log(data)
              },
            })
          }
        })
      </script>

Now the other problem is that when the user refreshes the page when he clicks the like button it goes by 1 just in the UI and not in the database, How can I save it so when he comes to an article he already liked, the button is different and when he clicks vote it goes down by 1.

Upvotes: 0

Views: 58

Answers (1)

Dimitar
Dimitar

Reputation: 520

You can add a querystring indicating which option the user chose to vote (upvote/downvote).

You can indicate that by adding ?type=downvote or ?type=upvote.(That's optional you can even type type=0/1). So it will be like url: 'vote/?type={upvote or downvote}',.

You need to distinguish between the 2 options in the javascript. I cannot give you examples here because I don't know the structure but it can be as basic as $("#upvote_button").click((e) => //ajax request and another one for the downvote button.

Now in the backend you would have your request.GET["type"] and you can decide based on that type if you want to upvote or downvote the article.

Upvotes: 1

Related Questions