title: Duplicate username client side validation in Django
body: <p>I would like to do a client side validation on a username field when the user is registering for an account. This validation should check if the username has been taken before the user submits the form. </p>
  
  <p>I have currently implemented basic client side validations using jQuery validate: <a href="http://jqueryvalidation.org/" rel="nofollow">http://jqueryvalidation.org/</a></p>
  
  <p>What is the recommended approach to accomplish this in Django? Is it possible to integrate this solution with jQuery validate?</p>
  
  <p><strong>Update</strong> Below is my js and html code:</p>
  
  <pre><code> &lt;script&gt;
      function getCookie(name) {
        var cookieValue = null;
        if (document.cookie &amp;&amp; document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i &lt; cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
      }
  
      var csrftoken = getCookie('csrftoken');
  
  
      function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }
      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) &amp;&amp; !this.crossDomain) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        }
      });
  
  
      $(document).ready(function () {
        $('#register-form').validate({ // initialize the plugin
          rules: {
            username: {
              required: true,
              remote: {
                url: "/check-username",
                type: "post",
                data: {
                  username: function() {
                    return $( "#id_username" ).val();
                  }
                }
              }
            }
          }
        });
      });
    &lt;/script&gt;
  </code></pre>
  
  <p>HTML: </p>
  
  <pre><code>&lt;form action="/accounts/register/" id="register-form" method="post"&gt;{% csrf_token %}
    {{form.username}}
    ...
  &lt;/form&gt;
  </code></pre>
  
  <p>Also, here is the view that does part of the validation:</p>
  
  <pre><code>def check_username(request):
      username = request.POST.get('username', False)
      if not username:
          return HttpResponseBadRequest("Invalid username")
      return HttpResponse(User.objects.filter(username=username).exists())
  </code></pre>