In my django app I have a form where I ask users to enter an email adress and a username.
I would like to be able to check if the username or the email adress already exist an raise an error they do. But I would like to do this without reloading my page, so using javascript or Jquery.
My first idea would be to be something like this (for username):
html:
<form method="post" onsubmit="return validateForm();">
{% csrf_token %}
<div id='error_message'></div>
<input class='username' type="text" name="username" value=""/>
<button type="submit">Valider</button>
</form>
In my views.py:
def myview(request):
users = User.objects.all()
return render_to_response('mytemplate.html', 'users':users, context_instance=RequestContext(request))
Then in my template:
<div class='search'>
{% for user in users %}
<input type='hidden' value='{{user.username}}'
{% endfor %}
</div>
And then, in the js:
function validateForm() {
var value = $('.username').val()
if( // find 'value' in all the <input type='hidden'> ) {
var error = 'Username already exists';
$("#error_message").html(error);
return false;
}
};
I think this is quite complex. Is there a simpler way to accomplish that?
Thank for your help.