• 一个长得很丑的登录和注册


    1.登录

    ajax

    <script>
        $(function () {
            //登录按钮点击ajax请求
            $(".login_btn").click(function () {
                $.ajax({
                    url:"",
                    type:"post",
                    contentType:"json",
                    headers:{
                        "X-CSRFToken":$.cookie("csrftoken")
                    },
                    data:JSON.stringify({
                        user:$("#user").val(),
                        pwd:$("#pwd").val(),
                        validcode:$("#validcode").val(),
                    }),
                    success:function (response) {
                        if(response.user){
                            location.href = "http://www.baidu.com"
                        }else {
                            $(".error").html(response.err_msg).css("color","red")
                        }
                    }
                })
            })
    
            //点击验证码刷新
            $(".img").click(function () {
                this.src+="?"
            })
        })
    </script>

    视图函数

    def login(request):
        if request.is_ajax():
            ret = json.loads(request.body)
            user = ret.get("user")
            pwd = ret.get("pwd")
            validcode = ret.get("validcode")
            res = {"user":None,"err_msg":""}
            if validcode.upper() == request.session.get("keep_str").upper():
                user_obj = auth.authenticate(username=user,password=pwd)
                if user_obj:
                    res["user"] = user
                else:
                    res["err_msg"] = "用户或密码错误!"
            else:
                res["err_msg"] = "验证码错误!"
            return JsonResponse(res)
        else:
            return render(request,"login.html")
    
    def get_valid_img(request):
        # 生成验证码
        # 引入图片模块,画笔,字体
        from PIL import Image,ImageDraw,ImageFont
        from io import BytesIO
    
        def get_random_color():
            return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
    
        img = Image.new("RGB",(350,38),get_random_color())
        dram = ImageDraw.Draw(img)
        font = ImageFont.truetype("static/font/kumo.ttf",32)
        keep_str = ""
        for i in range(6):
            random_num = str(random.randint(0,9))
            random_upperalf = chr(random.randint(65,90))
            random_loweralf = chr(random.randint(97,122))
            random_char = random.choice([random_num,random_loweralf,random_upperalf])
            dram.text((i*30+50,0),random_char,get_random_color(),font=font)
            keep_str += random_char
        # 线与点
        # width=350
        # height=38
        # for i in range(100):
        #     x1=random.randint(0,width)
        #     x2=random.randint(0,width)
        #     y1=random.randint(0,height)
        #     y2=random.randint(0,height)
        #     draw.line((x1,y1,x2,y2),fill=get_random_color())
        #
        # for i in range(500):
        #     draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        #     x = random.randint(0, width)
        #     y = random.randint(0, height)
        #     draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
        # 写与读
        f = BytesIO()
        img.save(f,"png")
        data = f.getvalue()
        # 将验证码存在session中
        request.session["keep_str"] = keep_str
    
        return JsonResponse(data)

    2.注册

    ajax

    <h3>注册界面</h3>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <form action="" method="post">
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label for="{{ field.id }}">{{ field.label }}</label>
                            {{ field }}
                            <span class="error"></span>
                        </div>
                    {% endfor %}
                    <input type="button" class="btn btn-primary pull-right reg_btn" value="注册">
                </form>
            </div>
        </div>
    </div>
    <script>
        $(function () {
            $(".reg_btn").click(function () {
                $.ajax({
                url:"",
                type:"post",
                contentType:"json",
                headers:{
                    "X-CSRFToken":$.cookie("csrftoken")
                },
                data:JSON.stringify({
                    username:$("#id_username").val(),
                    password:$("#id_password").val(),
                    r_password:$("#id_r_password").val(),
                    email:$("#id_email").val(),
                }),
                success:function (response) {
                    if (response.status == 200){
                        location.href = "{% url "login" %}"
                    }else if(response.status == 201){
                        //清除错误
                        $(".error").html("");
                        $(".form-control").removeClass("has-error")
                        //展示新的错误
                        $.each(response.err_msg,function (i,j) {
                            $("#id_"+i).next().html(j[0]).css("color","red").parent().addClass("has-error")
                        })
                    }
                }
            })
            })
    
        })
    </script>

    form组件

    class UserForm(forms.Form):
        username = forms.CharField(min_length=5,label="用户名",
                                   error_messages={
                                       "required": "用户名不能为空!",
                                       "min_length": "用户名不能少于5位!"
                                   }
                                   )
        password = forms.CharField(min_length=5,label="密码",widget=widgets.PasswordInput(),
                                   error_messages={
                                       "required":"密码不能为空!",
                                       "min_length":"密码不能少于5位!"
                                   })
        r_password = forms.CharField(min_length=5,label="确认密码",widget=widgets.PasswordInput(),
                                     error_messages={
                                         "required": "确认密码不能为空!",
                                         "min_length": "确认密码不能少于5位!"
                                     }
                                     )
        email = forms.EmailField(label="邮箱",widget=widgets.EmailInput(),
                                 error_messages={
                                     "required":"邮箱不能为空!",
                                     "invalid":"邮箱格式错误!"
                                 })
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            for filed in self.fields.values():
                filed.widget.attrs.update({'class': 'form-control'})
    
        def clean_username(self):
            val = self.cleaned_data.get("username")
            user_obj = UserInfo.objects.filter(username=val).first()
            if user_obj:
                raise ValidationError("该用户名已经存在!")
            else:
                return val
    
        def clean_password(self):
            val = self.cleaned_data.get("password")
            if val.isdigit():
                raise ValidationError("密码不能是纯数字!")
            else:
                return val
    
        def clean_email(self):
            val = self.cleaned_data.get("email")
            res = re.search("w+@163.com$",val)
            if res:
                return val
            else:
                raise ValidationError("邮箱必须是163邮箱!")
    
        def clean(self):
            password = self.cleaned_data.get("password")
            r_password = self.cleaned_data.get("r_password")
            if password and r_password and password != r_password:
                # 给全局钩子的错误信息命名,不用再使用默认的__all__
                self.add_error("r_password",ValidationError("两次输入的密码不一致!"))
            else:
                return self.cleaned_data

    视图函数

    def reg(request):
        # 注册功能
        if request.method == "POST":
            ret = json.loads(request.body)
            form = UserForm(ret)
            res = {"status":200,"err_msg":""}
            if form.is_valid():
                del ret["r_password"]
                UserInfo.objects.create_user(**ret)
            else:
                res["status"] = 201
                res["err_msg"] = form.errors
            return JsonResponse(res)
        else:
            form = UserForm()
            return render(request,"reg.html",{"form":form})
  • 相关阅读:
    威胁情报网站
    python3实现telnet查看IP地址段端口开放情况
    python3实现指定IP多线程端口扫描
    安全网址导航
    python3调用exe程序编写cve20190708批量检测工具
    python3爬取网页中的邮箱地址
    黑客马拉松
    Nginx自定义模块编写:根据post参数路由到不同服务器
    Apache HTTP Server 与 Tomcat 的三种连接方式介绍
    Apache HTTP Server 与 Tomcat 的三种连接方式介绍
  • 原文地址:https://www.cnblogs.com/qq849784670/p/9911733.html
Copyright © 2020-2023  润新知