title: Django: ajax response for valid/available username/email during registration
body: <p>I am using jQuery to do some inline form validation during user registration to prevent form errors after posting by checking to see if:</p>
  <ul>
  <li>username is available</li>
  <li>email has not already been registered</li>
  </ul>
  <p>The idea is to give the user feedback before the form is submitted to prevent frustration.  The code is at the bottom.</p>
  <h3>Questions:</h3>
  <ul>
  <li>Is this a potential security problem?  I had the thought that someone looking at my javascript could find the url I am polling for the username/email confirmation and then use it themselves (I don't know why they would do this, but one never knows).</li>
  <li>If it is, what protections can I implement?  I had read a little about cross-site scripting protection but am not sure how it could be implemented in a AJAX request, such as this, or if it is even necessary.</li>
  </ul>
  <p>Thanks for your input.</p>
  <h3>Current Code:</h3>
  <p>I have defined the following view (which I took from some snippet, but can't recall where):</p>
  <pre><code>def is_field_available(request):
      if request.method == &quot;GET&quot;:
          get = request.GET.copy()
          if get.has_key('username'):
              name = get['username']
              if User.objects.filter(username__iexact=name) or \
                  UserProfile.objects.filter(display_name__iexact=name):
                  return HttpResponse(False)
              else:
                  return HttpResponse(True)
          if get.has_key('email'):
              email = get['email']
              if User.objects.filter(email__iexact=email):
                  return HttpResponse(False)
              else:
                  return HttpResponse(True)
  
      return HttpResponseServerError(&quot;Requires username or email to test&quot;)
  </code></pre>
  <p>Here is a sample of the jQuery code:</p>
  <pre><code>$.get('is-user-name-available/', { email: $(this).val() },
      function(data, status){
          if(data == &quot;True&quot;){
              $input.fieldValid();
          } else {
              $input.fieldInvalid(&quot;This email address has already been registered.  Try another or recover your password.&quot;);
          }
  });
  </code></pre>
  <p>Edit: updated the code and rephrased my questions. [<strong>10/07/09</strong>]</p>