1

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!

1
  • 2
    i think first assign the listaUsuarios to a javascript list and then iterate. You have to use special template syntax Commented Nov 16, 2017 at 14:18

1 Answer 1

3

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 }});
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! It's not working yet, could it be because the context is not in the template when the javascript is resolved? I get this error: (1062, "Duplicate entry 'user' for key 'username'")
No, and that error can't possibly have anything to do with this code.
If the javascript worked it should stop the post method and that error wouldn't appear so I guess it's something around the list of usernames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.