Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!