Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

89
Vistas
CS50 Web - Project 4 Network

I am currently working on the CS50 Web Project 4 - Network. The task is to design a twitter-like Network. Currently, I am stuck at the Like-Function.

I have a like-button and a counter of the likes. When I click the like-button, the counter on the page says "undefined". But when I reload the page, everything is fine and the like-count shows the right number of likes and also the like button has changed to an unlike button. Does anyone have an idea what the issues? I am stuck for days now and cannot figure it out. Any help is much appreciated.

Here is my code:

views.py

@csrf_exempt
def like(request, post_id):
    post = Post.objects.get(id=post_id)

    if request.method == "GET":
        return HttpResponseRedirect(reverse("index"))

    if request.method == "PUT":
        data = json.loads(request.body)
        if data.get("like"):
            Likes.objects.create(user=request.user, post=post)
            post.likes = Likes.objects.filter(post=post).count()
        else:
            Likes.objects.filter(user=request.user, post=post).delete()
            post.likes = Likes.objects.filter(post=post).count()
        post.save()
        return HttpResponse("done")

java.js

function like(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: true
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

function unlike(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: false
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

and on my html:

<div id="like_count{{post.id}}">Likes: {{ post.likes }}</div>

{% if liked %}
<button class="btn btn-outline-danger" id="unlike_button{{post.id}}" onclick="unlike('{{ post.id }}')">Unlike</button>

{% else %}
<button class="btn btn-outline-primary" id="like_button{{post.id}}" onclick="like('{{ post.id }}')">Like</button>

{% endif %}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. Your view only ever returns "done", not an object that would have a likes attribute.
    You may want something like return JSONResponse({"likes": post.likes}) instead.
  2. The value fetch() returns is a Response. (You're trying to access likes on it.) You'll need to await on res.json() to decode a JSON response into an object. (While at it, we can remove a bit of repetition in the code.)
function likeOrUnlike(id, like) {
  fetch(`/like/${id}`, {
    method: "PUT",
    body: JSON.stringify({ like: !!like }),
  })
    .then((resp) => resp.json())
    .then((post) => {
      document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

function like(id) {
  likeOrUnlike(id, true);
}

function unlike(id) {
  likeOrUnlike(id, false);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda