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

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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