• django Form 效验


    Django 登入效验

    .py

    from django import forms
    from student import models
    from django.core.exceptions import ValidationError
    from django.core.validators import RegexValidator
    
    
    class RegForm(forms.Form):
        username = forms.CharField(
            max_length=16,
            label="用户名",
            widget=forms.widgets.TextInput(attrs={"class": "form-control"},),
            error_messages={
                "max_length": "用户名最长16位",
                "required": "用户名不能为空",
            }
        )
        password = forms.CharField(
            min_length=6,
            max_length=10,
            label="密码",
            widget=forms.widgets.PasswordInput(attrs={"class": "form-control"},),
            error_messages={
                "max_length": "最小长度为6",
                "required": "密码不能为空",
            }
        )
        re_password = forms.CharField(
            min_length=6,
            max_length=10,
            label="确认密码",
            widget=forms.widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True),
            error_messages={
                "min_length": "密码最少6位",
                "required": "密码不能为空",
            }
        )
        gender = forms.ChoiceField(
            choices=(('男', "男"), ('女', "女")),
            label="性别",
            initial=1,
            widget=forms.widgets.RadioSelect
        )
        age = forms.CharField(
            max_length=10,
            label="年龄",
            widget=forms.widgets.TextInput(attrs={"class": "form-control"}),
    
        )
        addr = forms.CharField(
            max_length=32,
            label="地址",
            widget=forms.widgets.TextInput(attrs={"class": "form-control"}),
            error_messages={
                "required": "地址不能为空",
            }
        )
        phone = forms.CharField(
            label="手机",
            validators=[
                RegexValidator(r'^1[3-9][0-9]{9}$', '手机格式不正确')
            ],
            widget=forms.widgets.TextInput(attrs={"class": "form-control"}),
            error_messages={
                "required": "手机不能为空"
            }
        )
    
        # 重写username字段的局部钩子
        def clean_username(self):
            username = self.cleaned_data.get("username")
            is_exist = models.Student.objects.filter(username=username)
            if is_exist:
                # 表示用户名已注册
                self.add_error("username", ValidationError("用户名已存在!"))
            else:
                return username
    
            # 重写全局的钩子函数, 对确认密码做效验
        def clean(self):
            password = self.cleaned_data.get("password")
            re_password = self.cleaned_data.get("re_password")
            if re_password and re_password != password:
                self.add_error("re_password", ValidationError("两次密码不一致"))
            else:
                return self.cleaned_data
    View Code

    .html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册</title>
    
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="/static/mystyle.css">
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form novalidate action="/reg/" method="post" class="form-horizontal reg-form"> {# autocomplete="off"自动补全 #}
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="{{ form_obj.username.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.username }}
                        <span class="help-block">{{ form_obj.username.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.password.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.password }}
                        <span class="help-block">{{ form_obj.password.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.re_password.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.re_password }}
                        <span class="help-block">{{ form_obj.re_password.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.gender.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.gender.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.gender }}
                        <span class="help-block">{{ form_obj.gender.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.age.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.age.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.age }}
                        <span class="help-block">{{ form_obj.age.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.addr.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.addr.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.addr }}
                        <span class="help-block">{{ form_obj.addr.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <label for="{{ form_obj.phone.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.phone.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.phone }}
                        <span class="help-block">{{ form_obj.phone.errors.0 }}</span>
                    </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-success" id="reg-submit">注册</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="/static/jquery-3.3.1.js"></script>
    <script src="/static/bootstrap/js/bootstrap.min.js"></script>
    {#<script>#}
    {#    // 找到头像的input标签绑定change事件#}
    {#    $("#id_avatar").change(function(){#}
    {#        //alert("123")#}
    {#        // 1.读取你选中的那个文件#}
    {#        var fileReader = new FileReader();#}
    {#        // 取到你选中的那个文件#}
    {#        //console.log(this.files[0]);#}
    {#        //读取你选中的那个文件#}
    {#        fileReader.readAsDataURL(this.files[0]);// 读取文件是需要时间的#}
    {#        fileReader.onload = function () {#}
    {#            //2.登上一部读完文件之后才把文件加载到img标签中#}
    {#            $("#avatar-img").attr("src", fileReader.result);#}
    {#        };#}
    {#    });#}
    {#    // AJAX提交注册的数据#}
    {#    $("#reg-submit").click(function () {#}
    {#        // 取到用户发送的请求数据,向后端发送AJAX请求#}
    {#        //var username = $("#id_username").val();#}
    {#        //var password = $("#id_password").val();#}
    {#        //var re_password = $("#id_re_password").val()#}
    {#        //var email = $("#id_email").val();#}
    {##}
    {#        var formData = new FormData()#}
    {#        formData.append("username", $("#id_username").val());#}
    {#        formData.append("password", $("#id_password").val());#}
    {#        formData.append("re_password", $("#id_re_password").val());#}
    {#        formData.append("phone", $("#id_phone").val());#}
    {#        formData.append("email", $("#id_email").val());#}
    {#        formData.append("avatar", $("#id_avatar")[0].files[0]);#}
    {#        formData.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());#}
    {#        $.ajax({#}
    {#            url:"/reg/",#}
    {#            type:"post",#}
    {#            processData: false,// 告诉jQuery不要处理我的数据#}
    {#            contentType: false,// 告诉jQuery不要设置content类型#}
    {#            data:formData,#}
    {#            success:function (data) {#}
    {#                if(data.status){#}
    {#                    //有错误就展示错误#}
    {#                    //console.log(data.msg);#}
    {#                    //将报错信息写到页面上#}
    {#                    $.each(data.msg, function (k,v) {#}
    {#                        $("#id_"+k).next("span").text(v[0]).parent().parent().addClass("has-error");#}
    {#                    })#}
    {#                }else{#}
    {#                    //没有错误就跳转到指定页面#}
    {#                    location.href = data.msg;#}
    {#                }#}
    {##}
    {#            }#}
    {#        });#}
    {#        //将所有的input框架定获取焦点事件,将所有的错误信息清空#}
    {#        $("form input").focus(function () {#}
    {#            $(this).next().text("").parent().parent().removeClass("has-error");#}
    {#        })#}
    {#    });#}
    {#    // 给username input框绑定一个时区焦点的事件, 失去焦点之后就效验用户名是否存在#}
    {#    $("#id_username").blur(function() {#}
    {#        //$("#id_username").on("input", function () {}) 边写边效验#}
    {#        //alert(123);失去焦点就弹窗#}
    {#        //取到用户填的值#}
    {#        var username = $(this).val();#}
    {#        // 发请求#}
    {#        $.ajax({#}
    {#            url: "/check_username_exist/",#}
    {#            type: "get",#}
    {#            data: {"username": username},#}
    {#            success: function (data) {#}
    {#                if (data.status) {#}
    {#                    //用户名已被注册#}
    {#                    $("#id_username").next().text(data.msg).parent().parent().addClass("has_error");#}
    {#                }#}
    {#            }#}
    {#        })#}
    {#    })#}
    {#</script>#}
    </body>
    </html>
    View Code
    此时此刻,非我莫属
  • 相关阅读:
    jquery 异常
    easyui datagrid 单击行不选择行
    java 简单实现上传 | commons-fileupload
    abator ibatis 构建过程
    mysql 杂笔
    eclipse杂笔
    maven 构建项目
    ubuntu随笔
    powershell:convert-path
    maven学习笔记1
  • 原文地址:https://www.cnblogs.com/taozhengquan/p/9825889.html
Copyright © 2020-2023  润新知