Django中重复的用户名客户端验证

时间:2015-09-28 19:00:18

标签: jquery python django validation

当用户注册帐户时,我想在用户名字段上进行客户端验证。此验证应检查在用户提交表单之前是否已使用用户名。

我目前使用jQuery validate实现了基本的客户端验证:http://jqueryvalidation.org/

在Django中实现此目的的推荐方法是什么?是否可以将此解决方案与jQuery验证集成?

更新以下是我的js和html代码:

 <script>
    function getCookie(name) {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < 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) && !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();
                }
              }
            }
          }
        }
      });
    });
  </script>

HTML:

<form action="/accounts/register/" id="register-form" method="post">{% csrf_token %}
  {{form.username}}
  ...
</form>

此外,以下是执行验证的部分视图:

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())

1 个答案:

答案 0 :(得分:0)

以下是文档中远程验证的改编示例:

http://jqueryvalidation.org/remote-method/

$( "#myform" ).validate({
  rules: {
    username: {
      required: true,
      email: true,
      remote: {
        url: "/check-username",
        type: "post",
        data: {
          username: function() {
            return $( "#username" ).val();
          }
        }
      }
    }
  }
});

然后您只需要一个视图

username = request.POST.get('username', None)
# probably you want to add a regex check if the username value is valid here
if not username:
    return HttpResponseBadRequest("Invalid username")
return HttpResponse(User.objects.filter(username=username).exists())