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

164
Vistas
How do I pass Django local variable of a funtion in views to javascript fetch API?

I am all new to javascript. I am making a like button that will increase the number of likes of a post asynchronously without reloading the whole page. Following is my Django views function.

views.py

@login_required
def likepost(request,id):
    post = NewPost.objects.get(id = id)
    is_like = False
    for like in post.likepost.all():
        if like == request.user and request.method == "POST":
            is_like = True
            break
    
    if not is_like:
        post.likepost.add(request.user)
    
    else:
        post.likepost.remove(request.user)
    
    return JsonResponse({
        "id" : id,
        "is_like" : is_like,
        "num_like" : post.likepost.count()
    })

Here id is the primary key of NewPost model. My javascript will fetch an API using this id variable. Here is my js function.

document.addEventListener("DOMContentLoaded",function(){
    document.querySelector('#like').addEventListener('click', ()=> like_function());
})


function like_function(){
    fetch(`index/${id}/like`)
    .then(response => response.json())
    .then(result => {
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Like";
        }
        else{
            document.querySelector('#like').innerHTML = "Unlike";
        }
    })
}
<button onclick="like_function()" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button>
    <small id="num_of_likes">{{ posts.likepost.all.count }}</small>
    {% block script %} 
        <script src="{% static 'network/controller.js' %}"></script>
    {% endblock %}
    <button class="btn btn-link" style="text-decoration: none;">Comment</button>
    <a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a>

Here, I've shared my javascript function as well as my HTML template. If I click the like button following message appears. enter image description here

What should I do now?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to add the item primary key in the like_function call:

<button onclick="like_function({{ posts.pk }})" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button>

then you define the like_function as:

function like_function(id) {
    fetch(`index/${id}/like`)
    .then(response => response.json())
    .then(result => {
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Like";
        }
        else{
            document.querySelector('#like').innerHTML = "Unlike";
        }
    })
}
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