Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

337
Visualizações
How do I increase database variable by 1 using put method is JS?

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")
]
about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda