简体   繁体   中英

Passing data through views context to javascript in Django

I'm trying to pass some data from the views.py to a template and using it in a javascript and I can't make it work. Does anyone know how can I solve this?

In the views.py

listaUsuarios = User.objects.values_list('username', flat=True)
context = {'listaUsuarios':listaUsuarios}

return render(request, redirect, context)

This actually works and if I do a print(listaUsuarios[2]) it shows just the username number 2 in the database.

The javascript in the template

function checkForm(form)
{
 for (i = 0; i < listaUsuarioss.length; i++) {
     if(form.username.value==listaUsuarioss[i]){
 alert("Error: El nombre de usuario ya está en uso");
       form.username.focus();
 return false;
 }
}
}

The invocation to the script

<form method="post" action="{% url 'register' %}" onsubmit="return checkForm(this,{‌{listaUsuarios}});"> 

I know I should have used Django forms for the registration but I didn't and I'm trying to make this work for checking before the registration of a new user if that username is already in use.

Thank you to everyone!

Your JavaScript doesn't have any access to Django template variables. You need to send the list as JSON, parse it in the JS and assign the result to a local variable there.

context = {'listaUsuarios': json.dumps(list(listaUsuarios))}

...

function checkForm(form) {
    var listaUsuarios = JSON.parse({{ listaUsarios|safe }});
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM