Django model not saving POST ajax request


I’m fairly new to ajax and Django please excuse my spaghetti code.

My Django model isn’t saving response even after getting a POST request. I’m trying to create a basic like , dislike counter and I’m having trouble updating my like value in database. Although I’m sending POST response to to function likePost in I can’t seem to update like_votes field in my Post model.

My model

class Post(models.Model):
    post_text = models.CharField(max_length=1000)
    pub_date = models.DateTimeField('date published')
    like_votes = models.IntegerField(default=0)
    dislike_votes = models.IntegerField(default=0)

    def was_published_recently(self):
        return self.pub_date >= - datetime.timedelta(days=1)

    def __str__(self):
        return self.post_text

My ajax function

        <script type="text/javascript">
            var likebtn = document.getElementById("likebtn");
            likebtn.addEventListener('click', buttonClikckHandler);

            var num1 = 1;
            var like = parseInt("{{post.like_votes}}");
            var new_l = like;

            function buttonClikckHandler() {
                console.log("clicked like");

                const xhr = new XMLHttpRequest();

                var new_l = like + num1 % 2;
                num1 = num1 + 1;
                document.getElementById("like").innerHTML = new_l;

                var catid;
                catid = $(this).attr("data-catid");
                        type: "GET",
                        url: "/likepost",
                        data: {
                            post_id: catid , 
                            votes : new_l
                        success: function (data) {
                            $('#like' + catid).remove();

                console.log(new_l, num1);


def likePost(request ):
    if request.method == 'POST':
           post_id = request.POST['post_id']
           print( post_id)
           likedpost = Post.objects.get(pk=post_id) 
           #m = Like(post=likedpost)
           likedpost.like_votes = int(request.POST['votes'])
           return HttpResponse("Success!") 
           return HttpResponse("Request method is not a POST")

Asked By: Shaswat Agrawal



You have made a mistake in the JS code. Ajax call should be POST instead of GET.

  type: "POST",
  url: "/likepost",
  data: {
    post_id: catid,
    votes: new_l,
  success: function (data) {
    $("#like" + catid).remove();
Answered By: Sazzad Hussain
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.