I am making a web app similar to twitter that allows users to like a post.
In order to make changes to the database, I created an API that allows one to use GET, PUT, or POST methods in order to access or make changes to the database.
I am using a Django Framework database and am using javascript to send fetch requests to the API.
My problem is that I am trying to use a put method to set the "likes" attribute of a post equal to 1 more than the previous number of likes the post had. I don't know how to do this.
Below is my javascript function that runs once a post is liked. I tried to access the number of likes a post has and set it equal to a variable. However, that is not working.
function likePost(postID) {
var postLikes;
fetch('/posts/' + postID)
.then(response => response.json())
.then(post => {
postlikes = post.likes
})
fetch('/posts/' + postID, {
method: 'PUT',
body: JSON.stringify({
likes: postLikes++,
liked: true
})
})
console.log(postLikes)
}
For some reason, the console.log returns NotaNumber, meaning that postlikes is not set equal to post.likes and is never instantiated. Thus, "likes" is never set equal to postLikes++ in the PUT method.
This is my Models.py file that defines the database
class Post(models.Model):
body = models.TextField(max_length=1000)
creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
timeStamp = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField()
liked = models.BooleanField(default=False)
def serialize(self):
return{
"id": self.id,
"creator": self.creator.username,
"body": self.body,
"timeStamp": self.timeStamp.strftime("%b %d %Y, %I:%M %p"),
"likes": self.likes,
"liked": self.liked
}
This is my urls.py file where the API routes are defined
urlpatterns = [
path("", views.index, name="index"),
path("create_post", views.create_post, name="create_post"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("test", views.test, name="test"),
#API routes
path("posts/<int:post_id>", views.post, name="post"),
path("posts", views.all_posts, name="all_posts")
]