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

191
Vistas
Why is the colour not saved? If the data is saved correctly

I'm making it save the colour in localStorage to see a red heart if liked and no colour if disliked after refreshing the web page. But I don't understand why it is not shown. I have debugged and the localSotage values are correct.

Index.js


const color = ["#000000", "#FF0000"];
let colorIndex = parseInt(localStorage.getItem("colorIndex")) || 0;
console.log("Initial: " + colorIndex);

function like(elem) {
    const postId = elem.attributes["data-id"].value
    const csrftoken = getCookie('csrftoken');
    fetch(`like/${postId}`, {
            method: 'POST',
            headers: { 'X-CSRFToken': csrftoken },
            mode: 'same-origin'
        }).then(res => res.json())
        .then(data => {
            document.getElementById(postId).innerText = data.numLikes
            console.log(data.liked + ", color: " + color[data.numLikes - 1]);
            if (data.liked == true) {
                colorIndex = data.isLiked;
                document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
                console.log("liked == true " + colorIndex);
            } else if (data.liked == false) {
                colorIndex = data.isLiked;
                document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
                console.log("liked == false " + colorIndex);
            }
            localStorage.setItem("colorIndex", colorIndex);
        })
}

views.py

 if request.method == "POST":
        postId = Post.objects.get(id = id) # Almacena los id de cada post
        if not postId.likes.filter(id = request.user.id).exists(): # Si no existe un like por el usuario
            newStatus = True
            isLiked = 1
            postId.likes.add(request.user) # Añadelo
            postId.save()
        else:
            newStatus = False
            isLiked = 0
            postId.likes.remove(request.user) # Si no lo quitas
            postId.save()

        return JsonResponse({"liked": newStatus, "isLiked": isLiked, "id": id, "numLikes": postId.likes.count()},status=200)
    return JsonResponse({"message": "Wrong method"}, status=400)
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You might have a syntax problem with your attribute setting.

Try:

setAttribute("style", "fill:" + color[colorIndex])

Bear in mind this may override any other style properties you don't include, so you can avoid that by settting fill directly:

document.getElementById(`icon-${postId}`).style.fill = color[colorIndex]

The other thing that might be causing you trouble is the fill is only being set in the like() function, presumably responding to clicking a like button of some sort. If the page is reloaded, there is nothing in the code shown that will test to see if the post has been liked - the colour set in the like() function won't persist after a page reload as it hasn't been called.

The best way to handle this is in the django template itself, seeing as you are storing the 'liked' data in the database. First, in your view, get a list of liked posts

In this example, 'likes' is a recordset passed to your template from your view - I'm assuming Likes is a ManyToMany field linking users to posts:

user_likes = Likes.objects.filter(id = request.user.id)

You can make the filter more specific for efficiency based on the page's requirements. Pass the result of this filter to the template via context.

When you come to display the post do something like:

<div class="post">
...
<img id="icon-{{post.id}}" class="
{% if post in user_likes %}
    liked
{% else %}
    notliked
{% endif %}
">
</div>

And have your classes defined in your CSS to include your fill values eg,

.liked {
    fill:#FF0000
}

.notliked {
    fill:#000000
}

This will handle your coloring without having to make any ajax type javascript calls

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