python_wayday14html-day5(form表单验证,)(代码片段)

author author     2022-11-29     340

关键词:

python-way day19 

1. dJango的form表单验证

 

 


 一,django表单验证功能

1、django验证基础:

技术分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>django form</title>
</head>
<body>
    <div>
        <input type="text" placeholder="用户名" name="user">
    </div>
    <div>
        <input type="password" placeholder="密码" name="password">
    </div>
    <input type="button" value="提交">
</body>
<script src="/statics/js/jquery-3.1.0.min.js"></script>
<script src="/statics/js/my_js.js"></script>
<script>
    $("div input").VelidForm("input[type=button]");   //使用jquery extend
    //把所有div下面的input作为筛选传过去,并且把点击的按钮作为参数传过去
</script>
</html>
django_form.html
技术分享
(function ($) 
    $.fn.extend(
        VelidForm: function (button)        //扩展方法
            var inps = this;                 //所有的用户输入框
            $(button).click(function ()     //点击事件绑定
                var input_dict = ;         //定义一个空字典
                $(inps).each(function ()    //循环所有input
                    var v = $(this).val();    //获取value
                    var k = $(this).attr("name");   //获取key
                    input_dict[k] = v;             //给字典赋值
                    );
                $.ajax(                                 //发送ajax请求
                    url: "/django_form/",
                    type: "POST",
                    data: input_dict,
                    dataType: "json",
                    //回调函数
                    success: function (data) 
                        //ajax提交成功调用这个函数

                    ,
                    error:function () 
                        //ajax失败自动调用这个函数
                    
                    )
            )
        
    );
)(jQuery);            
my_js.js
#定义验证规则
from django import forms      #需要倒入继承django给我们提供的forms
class LoginForm(forms.Form):
    user = forms.CharField(required=True)   #required = True 输入不能为空
    password = forms.CharField(required=True)


def django_form(request):
    if request.method == "POST":
        obj = LoginForm(request.POST)  #request.POST 里面有用户输入的所有信息
        ret = obj.is_valid()           #这样就验证了用户输入是否为空
        print(ret)                      #这样就能看到了返回值:True False
     if ret:
print(obj.clean()) #拿到正确的输入值
else:
     print(obj.errors)  #拿到错误值
    return render(request, "django_form.html")

只要有一项没有填写内容,ret就是False: 并且obj.errors 会把错误获取到 (password没有填写内容) 

技术分享

注意:匹配规则名称要统一

views:

技术分享

django_form.html

技术分享

 

2、获取错误信息

首先我们看到了我们获取到的错误信息时一个<ul><li>的类型,那么就说明了这个error里面应该有一个str方法,这个方法输出的就是这个类型,那我们来来看一下这个error

的类型,看看他的本质!

技术分享

是一个错误字典类型:

技术分享
 else:
            from django.forms.utils import ErrorDict
            print(type(obj.errors))
    return render(request, "django_form.html")

====================================

class ErrorDict(dict):
    """
    A collection of errors that knows how to display itself in various formats.

    The dictionary keys are the field names, and the values are the errors.
    """
    def as_data(self):
        return f: e.as_data() for f, e in self.items()

    def as_json(self, escape_html=False):
        return json.dumps(f: e.get_json_data(escape_html) for f, e in self.items())

    def as_ul(self):
        if not self:
            return ‘‘
        return format_html(
            <ul class="errorlist"></ul>,
            format_html_join(‘‘, <li></li>, ((k, force_text(v)) for k, v in self.items()))
        )

    def as_text(self):
        output = []
        for field, errors in self.items():
            output.append(* %s % field)
            output.append(\n.join(  * %s % e for e in errors))
        return \n.join(output)

    def __str__(self):
        return self.as_ul()
ErrorDict

 

可以看到里面有很多的方法,默认str输出的是al_ul,如果我们想要as_json,我们也可以获取到 

def django_form(request):
    if request.method == "POST":
        obj = LoginForm(request.POST)  #request.POST 里面有用户输入的所有信息
        ret = obj.is_valid()           #这样就验证了用户输入是否为空
        if ret:
            print(obj.clean())
        else:
            print(obj.errors.as_json())   #这样我们就获得了json格式的错误提示
    return render(request, "django_form.html")

技术分享

#定义验证规则
from django import forms      #需要倒入继承django给我们提供的forms
import json
class LoginForm(forms.Form):
    user = forms.CharField(required=True)   #required = True 输入不能为空
    password = forms.CharField(required=True)


def django_form(request):
    if request.method == "POST":
        obj = LoginForm(request.POST)  #request.POST 里面有用户输入的所有信息
        ret = obj.is_valid()           #这样就验证了用户输入是否为空
        result = "status":False,"message":None
        if ret:
            result["status"] = True
            print(obj.clean())
        else:
            error_str = obj.errors.as_json()
            print(obj.errors.as_json())
            result["message"] = json.loads(error_str)
        return HttpResponse(json.dumps(result))
    return render(request, "django_form.html")

前端js

技术分享
(function ($) 
    $.fn.extend(
        VelidForm: function (button)        //扩展方法
            var inps = this;                 //所有的用户输入框
            $(button).click(function ()     //点击事件绑定
                var input_dict = ;         //定义一个空字典
                $(inps).each(function ()    //循环所有input
                    var v = $(this).val();    //获取value
                    var k = $(this).attr("name");   //获取key
                    input_dict[k] = v;             //给字典赋值
                    );
                $(.error-msg).remove();
                $.ajax(
                    url: "/django_form/",
                    type: "POST",
                    data: input_dict,
                    dataType: "json",   //这样指定了数据的格式是json
                    //回调函数
                    success: function (data) 
                        //ajax提交成功调用这个函数
                        if(data.status)
                            location.href = "/index/";
                        else
                        $.each(data.message, function (k,v)    //拿到的是一个字典,循环这个字典,获取它的k和v
                            //"user": ["code": "required", "message": "This field is required."],
                            // "password": ["code": "required", "message": "This field is required."]
                            console.log(k,v[0].message);  //获取message内容
                            var tag = document.createElement(span);   //dom创建标签
                            tag.className = error-msg;                //添加样式
                            tag.innerText = v[0].message;               //插入内容
                            // $(inps[name=" + k + "]).after(tag)   字符串的拼接(字符窜拼接的例子,这里没有用到)
                            $(inps).each(function ()                   //循环传过来的input标签
                                if($(this).attr("name") == k )          //如果这个当前循环到的标签的name = 上面我们循环的k则在他后面添加一个错误信息
                                    $(this).after(tag)
                                
                            )
                        );

                        // JSON.parse(data) 这样?可以转换成dict格式
                     
                    ,
                    error:function () 
                        //ajax失败自动调用这个函数
                    
                    )
            )
        
 
    );
)(jQuery);
前端 js - 使用默认的message信息

 

html-day2

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><h2>RegisPage</h2><fromaction=""method="post"> 查看详情

html-day3

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>test</title><style>li{list-style:none;}.yema{width:20px;/*设置宽度*/height:20px;/*设置高度*/color:aqua; 查看详情

html-day-4-表单

表单使用<form>标签定义一个表单,格式为:<formid=""name="表单类型"method="表单的提交方式"action="提交的地址">表单内容</form>一、属性:①id不可重复②name可重复③method,有两种提交方式:get&post,get提交方式有长... 查看详情

html-day-2-html常用标签

一、常用标签超链接标签 href-----hyperlinkreference_blank,是指在新窗口中打开。  作用:①做锚点的标签,<aname=””></a>        ②做锚点链接,<ahref=”目标链接的n 查看详情

mysql控制语句

14.6.5.1CASESyntax14.6.5.2IFSyntax14.6.5.3ITERATESyntax14.6.5.4LEAVESyntax14.6.5.5LOOPSyntax14.6.5.6REPEATSyntax14.6.5.7RETURNSyntax14.6.5.8WHILESyntaxCASE用法:两种用法: IF用法:循环语句:ITERATESyntaxITERATE仅 查看详情

AuthenticationException:AuthenticationMechanismTooWeak:5.7.14

】AuthenticationException:AuthenticationMechanismTooWeak:5.7.14【英文标题】:AuthenticationException:AuthenticationMechanismTooWeak:5.7.14【发布时间】:2018-03-1920:01:44【问题描述】:我在Web应用程序上使用MVCASP.NETCore1.1.2。我尝试使用MailKit1.18.1.1创建... 查看详情

带有命名参数的 PySide2 (5.14.2) 信号

】带有命名参数的PySide2(5.14.2)信号【英文标题】:PySide2(5.14.2)signalwithnamedparameter【发布时间】:2020-04-0312:20:54【问题描述】:PySideSignalargumentcan\'tberetrievedfromQML根据这篇文章,PySide2(版本>5.12.5)支持带有命名参数的信号,如Py... 查看详情

习题5-14

#include"stdafx.h"#include<iostream>usingnamespacestd;classBoat;classCar{private:intweight;public:Car(intj){weight=j;}friendintgetTotalWeight(Car&aCar,Boat&aBoat);};classBoat{private:int 查看详情

决策数题目(是否适合打网球)简单学习-手算(代码片段)

题目: 大致结果手绘图: 详细计算过程: 一级筛选:一级筛选1.天气frommathimport*sum=-(9/14)*log(9/14,2)-(5/14)*log(5/14,2)a=5/14*(-(2/5)*log(2/5,2)-(3/5)*log(3/5,2))#晴b=4/14*(-1*log(1,2))#阴c=5/14*(-(3/5)*log(3/5,2)-( 查看详情

SunCC 5.12 到 5.14 和“不能在匿名联合中声明类型”

】SunCC5.12到5.14和“不能在匿名联合中声明类型”【英文标题】:SunCC5.12through5.14and"Typescannotbedeclaredinanonymousunion"【发布时间】:2016-09-1507:41:30【问题描述】:我们在SunCC5.12到5.14下发现了一个编译警告。其他编译器,如Clan... 查看详情

尝试安装 libwww-perl 时构建 Docker 映像会导致错误,即 perl-modules_5.14.2-6 和 perl_5.14.2-6 Not found

】尝试安装libwww-perl时构建Docker映像会导致错误,即perl-modules_5.14.2-6和perl_5.14.2-6Notfound【英文标题】:BuildingaDockerImageresultsinerrorwhiletryingtoinstalllibwww-perli.e.,perl-modules_5.14.2-6andperl_5.14.2-6Notfound【发布时间】:2016-06-3017:5 查看详情

无法在 Ubuntu 14.04 上安装 Mysql 5.6

】无法在Ubuntu14.04上安装Mysql5.6【英文标题】:Can\'tInstallMysql5.6onUbuntu14.04【发布时间】:2015-09-2304:54:38【问题描述】:我正在尝试在Ubuntu14.04上从Mysql5.5升级到Mysql5.6我试过了:直接使用sudoapt-getinstallmysql-server-5.6安装-不成功首先... 查看详情

ios14.5.1导致手机性能节流,手机变卡怎么办?

参考技术A近几天苹果官方刚发布了iOS14.5.1正式版系统,在原有的iOS14.5正式版系统上进行了bug修复,但是新发布的iOS14.5.1系统上也出现了一个不小的bug。那就是iPhone11和iPhone12系列机型的用户升级iOS14.5.1后,部分用户可能会遇到性... 查看详情

intellijidea14.1.5怎样设置中文

参考技术A在网上搜索idea汉化包,下载下来,然后将其放置在lib目录下,重启idea。完成。 查看详情

rpm安装pdksh-5.2.14报错:“faileddependencies:”

1.安装pdksh-5.2.14-37.el5_8.1.x86_64.rpm[[email protected] ~]# rpm -lvh pdksh-5.2.14-37.el5_8.1.x86_64.rpm  rpm: --hash (-h) may only be  查看详情

相容问题(代码片段)

...别为(1,4),(3,5),(5,7),(0,6),(3,8),(5,9),(8,11),(6,10),(8,12),(2,13),(12,14)如果按照每项活动的结束时间从小到大排序后的顺序进行。则顺序为(1,4),(3,5),(0,6),(5,7),(3,8),(5,9),(6,10),(8,11),(8,12),(2,13),(12,14),则可以安排的活动有4个,分别为(1,4),(5,7),(8,1... 查看详情

相容问题(代码片段)

...别为(1,4),(3,5),(5,7),(0,6),(3,8),(5,9),(8,11),(6,10),(8,12),(2,13),(12,14)如果按照每项活动的结束时间从小到大排序后的顺序进行。则顺序为(1,4),(3,5),(0,6),(5,7),(3,8),(5,9),(6,10),(8,11),(8,12),(2,13),(12,14),则可以安排的活动有4个,分别为(1,4),(5,7),(8,1... 查看详情

ubuntu 14.04 上的 Laravel 5.1 会话问题

】ubuntu14.04上的Laravel5.1会话问题【英文标题】:Laravel5.1onubuntu14.04Problemswithsession【发布时间】:2015-11-1415:51:35【问题描述】:我在ubuntu14.04上的laravel(5.1)会话存在以下问题。每个请求都会在storage/framework/sessions中生成一个新的会... 查看详情