简体   繁体   中英

Jquery form validation with Django

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.

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 eg django-usernea django-allauth

I would go with ajax validation:

First give your form an id eg 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')

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