0

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.

1
  • you could make an ajax call via jquery to a view which checks whether the user exist and the username can be taken and return this result to your script. Commented Dec 17, 2012 at 23:45

1 Answer 1

5

Sorry to say but your approach is very bad in terms of security and efficiency. You are disclosing all the usernames of your users (no matter if hidden input). You should check some already built authentication apps e.g django-usernea django-allauth

I would go with ajax validation:

First give your form an id e.g. my_form

<script>
    $('#my_form').submit(function(){
      var username = $('#username').val();
      if (username == ''){
         alert('please enter username');
         return false;
      }

      $.ajax({
               type: "POST",
               url: "{% url auth_validate %}",
               data: {'username': $('#username').val(), 'csrfmiddlewaretoken': '{{csrf_token}}'},
               dataType: "text",
               success: function(response) {
                      var response = $.parseJSON( response );
                      if (response.success){
                          return true;
                      }
                      else{
                          alert(response.error);
                      }
                },
                error: function(rs, e) {
                       alert(rs.responseText);
                }
          }); 
    })
</script>

In urls.py add auth_validate url:

url(r'^auth_validate/$', 'myapp.views.auth_validate', name='auth_validate'),

Now in myapp.views:

from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _

def auth_validate(request):
    error = ''
    success = False
    if request.method == 'POST':
        username = request.POST.get('username', None)
        if not username:
            error = _('Please enter username')
        elif User.objects.filter(username__exact=username).exists():
            error = _('Sorry this username is already taken')
        else:
            success = True

    ajax_vars = {'success': success, 'error': error}
    return HttpResponse(simplejson.dumps(ajax_vars),
                    mimetype='application/javascript')
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your help. I get the first part where you use a post method. In my view, I will have to check if 'username' is already in use. The thing I don't get is how I get the response back to my script (if it is in use or not)? I think the second part of your ajax request handles that, but I don't get how it works. Could you give me some explanation about that?
@Marcolac I have added the complete example code. I have just tried to validate the username, but you can validate the more things in similar fashion. Hope this will help now.
Since yesterday I try to make it work but sadly I didn't manage. When I try your solution, I just have an empty alert that appears after I enter a username (that exists or not) and then the form is submited. I don't know where the error comes from. Do you have any idea on why it doesn't work? Thank you!
I think something is missing here. Prevent the form from being submited if the username exists. But thanks for your code, it helped me a lot.

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.