最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery form validation with Django - Stack Overflow

programmeradmin1浏览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 plex. Is there a simpler way to acplish that?

Thank for your help.

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 plex. Is there a simpler way to acplish that?

Thank for your help.

Share asked Dec 17, 2012 at 23:27 MarcolacMarcolac 9314 gold badges15 silver badges29 bronze badges 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. – Jingo Commented Dec 17, 2012 at 23:45
Add a ment  | 

1 Answer 1

Reset to default 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')
发布评论

评论列表(0)

  1. 暂无评论