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 view.py 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 >= timezone.now() - 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");
$.ajax(
{
type: "GET",
url: "/likepost",
data: {
post_id: catid ,
votes : new_l
},
success: function (data) {
$('#like' catid).remove();
$('#message').text(data);
}
})
console.log(new_l, num1);
}
</script>
Views.py
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'])
likedpost.save()
#m.save()
return HttpResponse("Success!")
else:
return HttpResponse("Request method is not a POST")
CodePudding user response:
You have made a mistake in the JS code. Ajax call should be POST
instead of GET
.
$.ajax({
type: "POST",
url: "/likepost",
data: {
post_id: catid,
votes: new_l,
},
success: function (data) {
$("#like" catid).remove();
$("#message").text(data);
},
});