Django基础(五)- form组件及django序列化

一、form组件功能

Django的Form组件主要有以下几大功能:

1)生成HTML标签

2)验证用户数据(显示错误信息)

3)HTML Form提交保留上次提交数据

4)初始化页面显示内容

二、小试牛刀

2.1、创建Form类

###########################views.py#####################################
from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import fields

class F1Form(forms.Form):
    user = fields.CharField(
        max_length=18,
        min_length=6,
        required=True,
        error_messages={
            'required': '用户名不能为空',
            'max_length': '太长了',
            'min_length': '太短了'
        }
    )
    pwd = fields.CharField(
        required=True,
        min_length=32,
        error_messages={
            'required': '密码不能为空',
            'min_length': '太短了'
        }

    )
    age = fields.IntegerField(
        required=True,
        error_messages={
            'required': '年龄不能为空',
            'invalid': '不许为数字',
        }
    )
    email = fields.EmailField(
        required=True,
        error_messages={
            'required': '邮箱不能为空',
            'invalid': '邮箱格式错误'
        }
    )

2.2、View函数处理

def f1(request):
    if request.method == 'GET':
        obj = F1Form()  #创建html
        return render(request,'f1.html',{'obj':obj})
    else:
        # u = request.POST.get('user') #不能为空,长度6-18
        # p = request.POST.get('pwd')  #不能为空,长度32
        # e = request.POST.get('email') #不能为空,邮箱格式
        # a = request.POST.get('age')  #不能为空,数字类型
        # #1.检查是否为空
        # #2.检查格式是否正确
        # #models.TB.objects.create(**{'username':xxx})
        # print(u,p,e,a)

        obj = F1Form(request.POST)  #前端数据验证
        #是否全部验证成功
        if obj.is_valid():
            #用户提交的数据
            print("验证成功",obj.cleaned_data)
            return redirect('http://www.xiaohuar.com')
        else:
            print("验证失败",obj.errors)
            return render(request,'f1.html',{'obj':obj})

2.3、url配置

from django.contrib import admin
from django.urls import path
from app01 import views
from app02 import views as v2

urlpatterns = [
    path('admin/', admin.site.urls),
    # path('index.html/', views.index),
    # path('index1.html/', views.index1),
    path('index2.html/', views.index2),
    path('f1.html', v2.f1),
]

2.4、生成HTML

###########################html#####################################			
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#<form id="fm" action="/f1.html" method="POST">#}
{#    <p>用户<input type="text" name="user"/>{{ obj.errors.user.0 }}</p>#}
{#    <p>密码<input type="text" name="pwd"/>{{ obj.errors.pwd.0 }}</p>#}
{#    <p>年龄<input type="text" name="age"/>{{ obj.errors.age.0 }}</p>#}
{#    <p>邮箱<input type="text" name="email"/>{{ obj.errors.email.0 }}</p>#}
{#    <input type="submit" value="提交"/>#}
{#    <input type="button" value="Ajax提交" onclick="submitAjaxForm();"/>#}
{#</form>#}
{#<hr>#}

{#创建html#}
<form id="fm" action="/f1.html" method="POST">
    <p>用户{{ obj.user }}{{ obj.errors.user.0 }}</p>
    <p>密码{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
    <p>年龄{{ obj.age }}{{ obj.errors.age.0 }}</p>
    <p>邮箱{{ obj.email }}{{ obj.errors.email.0 }}</p>
    <input type="submit" value="提交"/>
{#    <input type="button" value="Ajax提交" onclick="submitAjaxForm();"/>#}
</form>
<script src="/static/jquery-3.1.1.js"></script>
<script>
    {#function submitAjaxForm(){#}
    {#    $.ajax({#}
    {#        url: '/f1.html',#}
    {#        type: 'POST',#}
    {#        data: $('#fm').serialize(),#}
    {#        success:function(arg){#}
    {#            console.log(arg);#}
    {#        }#}
    {#    })#}
    {#}#}
</script>
</body>
</html>

2.5、效果展示

image

2.6、示例二

1)url配置

from django.contrib import admin
from django.urls import path,re_path
from app01 import  views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', views.users),
    path('add_user/', views.add_user),
    re_path('edit_user-(\d+)/', views.edit_user),
]

2)视图函数

from django.shortcuts import render,HttpResponse,redirect
from app01 import models

def users(request):
    user_list = models.UserInfo.objects.all()
    return render(request,'users.html',{'user_list':user_list})

from app01.forms import UserForm
def add_user(request):
    if request.method == 'GET':
        obj = UserForm()
        return render(request,'add_user.html',{'obj':obj})
    else:
        obj = UserForm(request.POST)
        if obj.is_valid():
            # print(obj.cleaned_data) #{'user': 'yuan', 'email': '352972405@qq.com'}
            # models.UserInfo.objects.create(
            #     username=obj.cleaned_data['user'],
            #     email=obj.cleaned_data['email']
            # )
            models.UserInfo.objects.create(**obj.cleaned_data)  #写入数据库
            return redirect('/users/')
        else:
            return render(request,'add_user.html',{'obj':obj})

def edit_user(request,nid):
    if request.method == 'GET':
        # nid = request.GET.get('nid')
        data = models.UserInfo.objects.filter(id=nid).first()
        obj = UserForm({'username':data.username,'email':data.email}) #设置默认值
        return render(request,'edit_user.html',{'obj':obj,'nid':nid})
    else:
        obj = UserForm(request.POST)
        if obj.is_valid():
            models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect('/users/')
        else:
            return render(request, 'edit_user.html', {'obj': obj, 'nid': nid})

3)数据库

from django.db import models

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)

    def __str__(self):
        return self.username

4)html编写

######################################users.html######################################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/add_user/">添加<a/>
<ul>
    {% for row in user_list %}
        <li>{{ row.id }}-{{ row.username }}-{{ row.email }}
            <a href="/edit_user-{{ row.id }}/">编辑</a>
        </li>
    {% endfor %}
</ul>

</body>
</html>

######################################add_user.html######################################

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/add_user/" method="POST" novalidate>
        {% csrf_token %}
        <p>用户{{ obj.username }}{{ obj.errors.username.0 }}</p>
        <p>邮箱{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

######################################edit_user.html######################################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/edit_user-{{ nid }}/" method="POST" novalidate>
        {% csrf_token %}
        <p>{{ obj.username }}{{ obj.errors.username.0 }}</p>
        <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

三、Form类

创建Form类时,主要涉及到 【字段】【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML;

3.1、Django内置字段

Field
    required=True,               是否允许为空
    widget=None,                 HTML插件
    label=None,                  用于生成Label标签或显示内容
    initial=None,                初始值
    help_text='',                帮助信息(在标签旁边显示)
    error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
    show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
    validators=[],               自定义验证规则
    localize=False,              是否支持本地化
    disabled=False,              是否可以编辑
    label_suffix=None            Label内容后缀
 
 
CharField(Field)
    max_length=None,             最大长度
    min_length=None,             最小长度
    strip=True                   是否移除用户输入空白
 
IntegerField(Field)
    max_value=None,              最大值
    min_value=None,              最小值
 
FloatField(IntegerField)
    ...
 
DecimalField(IntegerField)
    max_value=None,              最大值
    min_value=None,              最小值
    max_digits=None,             总长度
    decimal_places=None,         小数位长度
 
BaseTemporalField(Field)
    input_formats=None          时间格式化   
 
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
 
DurationField(Field)            时间间隔:%d %H:%M:%S.%f
    ...
 
RegexField(CharField)
    regex,                      自定制正则表达式
    max_length=None,            最大长度
    min_length=None,            最小长度
    error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
 
EmailField(CharField)      
    ...
 
FileField(Field)
    allow_empty_file=False     是否允许空文件
 
ImageField(FileField)      
    ...
    注:需要PIL模块,pip3 install Pillow
    以上两个字典使用时,需要注意两点:
        - form表单中 enctype="multipart/form-data"
        - view函数中 obj = MyForm(request.POST, request.FILES)
 
URLField(Field)
    ...
 
 
BooleanField(Field)  
    ...
 
NullBooleanField(BooleanField)
    ...
 
ChoiceField(Field)
    ...
    choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默认select插件
    label=None,                Label内容
    initial=None,              初始值
    help_text='',              帮助提示
 
 
ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查询数据库中的数据
    empty_label="---------",   # 默认空显示内容
    to_field_name=None,        # HTML中value的值对应的字段
    limit_choices_to=None      # ModelForm中对queryset二次筛选
     
ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField
 
 
     
TypedChoiceField(ChoiceField)
    coerce = lambda val: val   对选中的值进行一次转换
    empty_value= ''            空值的默认值
 
MultipleChoiceField(ChoiceField)
    ...
 
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val   对选中的每一个值进行一次转换
    empty_value= ''            空值的默认值
 
ComboField(Field)
    fields=()                  使用多个验证,如下:即验证最大长度20,又验证邮箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
 
MultiValueField(Field)
    PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
 
SplitDateTimeField(MultiValueField)
    input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
    input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
 
FilePathField(ChoiceField)     文件选项,目录下文件显示在页面中
    path,                      文件夹路径
    match=None,                正则匹配
    recursive=False,           递归下面的文件夹
    allow_files=True,          允许文件
    allow_folders=False,       允许文件夹
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''
 
GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
 
SlugField(CharField)           数字,字母,下划线,减号(连字符)
    ...
 
UUIDField(CharField)           uuid类型,UUID是根据MAC以及当前时间等创建的不重复的随机字符串
    ...

注意:UUID是根据MAC以及当前时间等创建的不重复的随机字符串

>>> import uuid

    # make a UUID based on the host ID and current time
    >>> uuid.uuid1()    # doctest: +SKIP
    UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

    # make a UUID using an MD5 hash of a namespace UUID and a name
    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
    UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

    # make a random UUID
    >>> uuid.uuid4()    # doctest: +SKIP
    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

    # make a UUID using a SHA-1 hash of a namespace UUID and a name
    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
    UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

    # make a UUID from a string of hex digits (braces and hyphens ignored)
    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

    # convert a UUID to a string of hex digits in standard form
    >>> str(x)
    '00010203-0405-0607-0809-0a0b0c0d0e0f'

    # get the raw 16 bytes of the UUID
    >>> x.bytes
    b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

    # make a UUID from a 16-byte string
    >>> uuid.UUID(bytes=x.bytes)
    UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

3.2、Django内置插件

TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget

常用插件

# 单radio,值为字符串
# user = fields.CharField(
#     initial=2,
#     widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
# )
 
# 单radio,值为字符串
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.RadioSelect
# )
 
# 单select,值为字符串
# user = fields.CharField(
#     initial=2,
#     widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
# )
 
# 单select,值为字符串
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.Select
# )
 
# 多选select,值为列表
# user = fields.MultipleChoiceField(
#     choices=((1,'上海'),(2,'北京'),),
#     initial=[1,],
#     widget=widgets.SelectMultiple
# )
 
 
# 单checkbox
# user = fields.CharField(
#     widget=widgets.CheckboxInput()
# )
 
 
# 多选checkbox,值为列表
# user = fields.MultipleChoiceField(
#     initial=[2, ],
#     choices=((1, '上海'), (2, '北京'),),
#     widget=widgets.CheckboxSelectMultiple
# )

实例:

1)视图views

from django.shortcuts import render
from django import forms
from django.forms import fields
from django.forms import widgets

class TestForm(forms.Form):
    user = fields.CharField(
        required=True,  #是否必填
        max_length=12,  #最大长度
        min_length=3,  #最小长度
        error_messages={}, #错误提示
        # widget = widgets.Textarea() #生成文本域 ==>定制html插件
        # widget = widgets.Select()  #生成下拉框
        widget=widgets.TextInput(attrs={'class':'c1'}),  #定制插件,定制属性
        label="用户名",
        initial="请输入用户名",  #设置默认值
        help_text="xajdkajd",  #没啥用
        show_hidden_initial=False, #是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
        # validators=[]   #可以自定制验证规则
        # localize=False   #是否支持本地化(本地时间,UTC时间)
        # disabled=True   #能否编辑
        label_suffix="==>"
    )

    age = fields.IntegerField(
        label='年龄',
        max_value=12,
        min_value=5,
        error_messages={
            'max_value':'太大了',
        }
    )
    email = fields.EmailField(
        label='邮箱'
    )

    img = fields.FileField()  #上传文件

    city1 = fields.ChoiceField(
        choices=[(1,'北京',),(2,'上海',),(3,'深圳',)],  #默认传过去的是字符串
        initial=2,  #默认选择上海
    )
    #'city1': '2', 'city2': 2,
    city2 = fields.TypedChoiceField(
        coerce=lambda x:int(x),   #将字符串转换为整形
        choices=[(1,'武汉',),(2,'成都',),(3,'广州',)],
        initial=2,  #默认选择上海
    )

    hobby = fields.MultipleChoiceField(
        choices=[(1,'AAA'),(1,'BBB'),(1,'CCC'),],
        initial=[1,2]  #设置默认值
    )

    xoo = fields.FilePathField(
        path='app01'   #列出目录下所有文件,不常用
    )

    #select框单选的几种写法
    xdb1 = fields.CharField(
        widget=widgets.Select(choices=[(1,'AAA'),(1,'BBB'),(1,'CCC'),])
    )

    xdb2 = fields.IntegerField(   #可以将字符串转换为整数
        widget=widgets.Select(choices=[(1,'AAA'),(1,'BBB'),(1,'CCC'),])
    )

    xdb3 = fields.ChoiceField(
        choices=[(1,'AAA'),(1,'BBB'),(1,'CCC')]
    )

    #select框多选
    mul = fields.MultipleChoiceField(
        choices=[(1,'AAA'),(1,'BBB'),(1,'CCC')],
        widget=widgets.SelectMultiple(attrs={'class':'c1'})
    )

    #单选checkbox
    cbx1 = fields.CharField(
        widget = widgets.CheckboxInput()
    )

    #多选checkbox
    cbx2 = fields.MultipleChoiceField(
        initial=[2,],
        choices=((1,'上海'),(2,'北京'),),
        widget=widgets.CheckboxSelectMultiple
    )

    #radio
    rad = fields.ChoiceField(
        choices=((1,'上海'),(2,'北京'),),
        initial=2,
        widget=widgets.RadioSelect
    )


def test(request):
    if request.method == 'GET':
        obj = TestForm()
        # obj = TestForm({'city':1})  #设置默认值
        txt = "<input type='text' />"
        from django.utils.safestring import mark_safe
        txt = mark_safe(txt)  #相当前端使用"|safe"
        return render(request,'test.html',{'obj':obj,'txt':txt})
    else:
        obj = TestForm(request.POST,request.FILES) #上传文件request.FILES
        obj.is_valid()
        print(obj.cleaned_data)
        return render(request, 'test.html', {'obj': obj})

2)html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ txt }}
<form method="POST" action="/test/" novalidate enctype="multipart/form-data">
    {% csrf_token %}
    <p>{{ obj.user.label }}{{ obj.user }}</p>
    <p>{{ obj.age.label }}{{ obj.age }}{{ obj.errors.age.0 }}</p>
    <p>{{ obj.email.label }}{{ obj.email }}</p>
    <p>{{ obj.img.label }}{{ obj.img }}</p>
    <p>{{ obj.city1.label }}{{ obj.city1 }}</p>
    <p>{{ obj.city2.label }}{{ obj.city2 }}</p>
    <p>{{ obj.hobby.label }}{{ obj.hobby }}</p>
    <p>{{ obj.xoo.label }}{{ obj.xoo }}</p>
    <p>{{ obj.xdb1.label }}{{ obj.xdb1 }}</p>
    <p>{{ obj.xdb2.label }}{{ obj.xdb2 }}</p>
    <p>{{ obj.xdb3.label }}{{ obj.xdb3 }}</p>
    <p>{{ obj.mul.label }}{{ obj.mul }}</p>
    <p>{{ obj.cbx1.label }}{{ obj.cbx1 }}</p>
    <p>{{ obj.cbx2.label }}{{ obj.cbx2 }}</p>
    <p>{{ obj.rad.label }}{{ obj.rad }}</p>
    <input type="submit" value="提交"/>
</form>
{#直接全部自动生成标签,不推荐 #}
{#{{ obj.as_p }}#}
{#{{ obj.as_ul }}#}
{#{{ obj.as_table }}#}
</body>
</html>

3)效果

image

四、动态绑定数据

在使用选择标签时,需要注意choices的选项可以从数据库中获取,但是由于是静态字段 ***获取的值无法实时更新***,那么需要自定义构造方法从而达到此目的。

4.1、方式一

定义构造方法,推荐

from app01 import models
class LoveForm(forms.Form):
    price = fields.IntegerField()
    user_id = fields.IntegerField(
        # widget=widgets.Select(choices=[(0,'AAA'),(1,'BBB'),(2,'CCC')])
        #从数据库中取值
        # widget=widgets.Select(choices=models.UserInfo.objects.values_list('id','username'))
        widget=widgets.Select()

    )

    #此时数据不能实时同步,需要自己手动同步
    #动态绑定数据方式一
    def __init__(self,*args,**kwargs):
        #拷贝所有的静态字段,复制给self.fields
        super(LoveForm,self).__init__(*args,**kwargs)
        #重新获取数据库值,不能写在super上面
        self.fields['user_id'].widget.choices=models.UserInfo.objects.values_list('id','username')

4.2、方式二

使用django提供的ModelChoiceField和ModelMultipleChoiceField字段来实现

from app01 import models
from django.forms.models import ModelChoiceField
class LoveForm(forms.Form):
    price = fields.IntegerField()
    user_id = fields.IntegerField(
        # widget=widgets.Select(choices=[(0,'AAA'),(1,'BBB'),(2,'CCC')])
        #从数据库中取值
        # widget=widgets.Select(choices=models.UserInfo.objects.values_list('id','username'))
        widget=widgets.Select()

    )

    #动态绑定数据方式二(不推荐),为了显示姓名,需要在定义的类C中定义__str__方法
    user_id2 = ModelChoiceField(
        queryset=models.UserInfo.objects.all(),
        to_field_name='id'
    )

#######################model.py################################
from django.db import models

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)
       
       #需要定义__str__
    def __str__(self):
        return self.username

五、ajax与form结合

1)视图

class AjaxForm(forms.Form):
    price = fields.IntegerField()
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=[(0,'AAA'),(1,'BBB'),(2,'CCC')])
    )

def ajax(request):
    if request.method == 'GET':
        obj = AjaxForm()
        return render(request,'ajax.html',{'obj':obj})
    else:
        ret = {'status': "AA",'message':None}
        import json
        obj = AjaxForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
            #此时不会跳转到百度
            # return redirect('http://www.baidu.com')
            ret['status'] = '钱'
            return HttpResponse(json.dumps(ret))
        else:
            # print(type(obj.errors))  #<class 'django.forms.utils.ErrorDict'>
            # print(obj.errors)
            from django.forms.utils import ErrorDict
            # print(obj.errors.as_ul())  #默认
            # print(obj.errors.as_json())
            # print(obj.errors.as_data())
            ret['message'] = obj.errors
            return HttpResponse(json.dumps(ret))

2)html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="fm" method="POST" action="/ajax/">
    {% csrf_token %}
{#    {{ obj.as_p }}#}
    <p>价格{{ obj.price }}</p>
    <p>姑凉{{ obj.user_id }}</p>
    <input type="button" value="Ajax提交" id="btn"/>
</form>
<script src="/static/jquery-3.1.1.js"></script>
<script>
    $(function () {
        $('#btn').click(function () {
            $.ajax({
                url: '/ajax/',
                type: 'POST',
                data: $('#fm').serialize(),
                dataType: 'JSON',
                success: function (arg) {
                    //arg需要包含状态,错误信息
                    if (arg.status == "钱") {
                        console.log(arg.status);
                        {#window.location.href = "http://www.baidu.com";#}
                        window.open("http://www.google.com")
                    }
                    console.log(arg)
                }
            })
        })
    })

</script>
</body>
</html>

六、自定义验证规则

6.1、简单扩展

利用Form组件自带的正则扩展

#方式一
    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator
     
    class MyForm(Form):
        user = fields.CharField(
            error_messages={'invalid': '...'},
            validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],
        )
#方式二
    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator
     
    class MyForm(Form):
        user = fields.RegexField(r'^[0-9]+$',error_messages={'invalid': '...'})

6.2、自定义函数

import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError
 
 
# 自定义验证规则
def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')
 
 
class PublishForm(Form):
 
 
    title = fields.CharField(max_length=20,
                            min_length=5,
                            error_messages={'required': '标题不能为空',
                                            'min_length': '标题最少为5个字符',
                                            'max_length': '标题最多为20个字符'},
                            widget=widgets.TextInput(attrs={'class': "form-control",
                                                          'placeholder': '标题5-20个字符'}))
 
 
    # 使用自定义验证规则
    phone = fields.CharField(validators=[mobile_validate, ],
                            error_messages={'required': '手机不能为空'},
                            widget=widgets.TextInput(attrs={'class': "form-control",
                                                          'placeholder': u'手机号码'}))
 
    email = fields.EmailField(required=False,
                            error_messages={'required': u'邮箱不能为空','invalid': u'邮箱格式错误'},
                            widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))

6.3、基于源码流程

验证过程有如下几个函数完成:

full_clean(self)

  1. self._clean_fields()
  2. self._clean_form()
  3. self._post_clean()

6.3.1、单字段验证

示例一:

from django import forms
    from django.forms import fields
    from django.forms import widgets
    from django.core.exceptions import ValidationError
    from django.core.validators import RegexValidator
 
    class FInfo(forms.Form):
        username = fields.CharField(max_length=5,
                                    validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.', 'invalid')], )
        email = fields.EmailField()
 
        def clean_username(self):
            """
            Form中字段中定义的格式匹配完之后,执行此方法进行验证
            :return:
            """
            value = self.cleaned_data['username']
            if "666" in value:
                raise ValidationError('666已经被玩烂了...', 'invalid')
            return value

示例二:

from django.core.exceptions import NON_FIELD_ERRORS, ValidationError

class AjaxForm(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=[(0,'AA'),(1,'BB'),(2,'CC'),])
    )
	
	# 自定义方法 clean_字段名
	# 必须返回值self.cleaned_data['username']
	# 如果出错:raise ValidationError('用户名已存在')
	def clean_username(self):
		v = self.cleaned_data['username']
		if models.UserInfo.objects.filter(username=v).count():
			# 整体错了
			# 自己详细错误信息
			raise ValidationError('用户名已存在')
		return v
		
	def clean_user_id(self):
		return self.cleaned_data['user_id']

6.3.2、整体错误验证

示例一:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
 
from django.core.validators import RegexValidator
 
 
############## 自定义字段 ##############
class PhoneField(fields.MultiValueField):
    def __init__(self, *args, **kwargs):
        # Define one message for all fields.
        error_messages = {
            'incomplete': 'Enter a country calling code and a phone number.',
        }
        # Or define a different message for each field.
        f = (
            fields.CharField(
                error_messages={'incomplete': 'Enter a country calling code.'},
                validators=[
                    RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
                ],
            ),
            fields.CharField(
                error_messages={'incomplete': 'Enter a phone number.'},
                validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
            ),
            fields.CharField(
                validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
                required=False,
            ),
        )
        super(PhoneField, self).__init__(error_messages=error_messages, fields=f, require_all_fields=False, *args,
                                         **kwargs)
 
    def compress(self, data_list):
        """
        当用户验证都通过后,该值返回给用户
        :param data_list:
        :return:
        """
        return data_list
 
############## 自定义插件 ##############
class SplitPhoneWidget(widgets.MultiWidget):
    def __init__(self):
        ws = (
            widgets.TextInput(),
            widgets.TextInput(),
            widgets.TextInput(),
        )
        super(SplitPhoneWidget, self).__init__(ws)
 
    def decompress(self, value):
        """
        处理初始值,当初始值initial不是列表时,调用该方法
        :param value:
        :return:
        """
        if value:
            return value.split(',')
        return [None, None, None]

实列二:定义clean()方法

class AjaxForm(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),])
    )

    # 自定义方法 clean_字段名
    # 必须返回值self.cleaned_data['username']
    # 如果出错:raise ValidationError('用户名已存在')
    def clean_username(self):
        v = self.cleaned_data['username']
        if models.UserInfo.objects.filter(username=v).count():
            # 整体错了
            # 自己详细错误信息
            raise ValidationError('用户名已存在')
        return v
    def clean_user_id(self):
        return self.cleaned_data['user_id']

    def clean(self):
        value_dict = self.cleaned_data
        v1 = value_dict.get('username')
        v2 = value_dict.get('user_id')
        if v1 == 'root' and v2==1:
            raise ValidationError('整体错误信息')   #浏览器显示__all__
        return self.cleaned_data

6.3.3、_post_clean方法

框架预留可自定义,不常用

七、初始化数据

在Web应用程序中开发编写功能时,时常用到获取数据库中的数据并将值初始化在HTML中的标签上。

7.1、Form

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator
 
 
class MyForm(Form):
    user = fields.CharField()
 
    city = fields.ChoiceField(
        choices=((1, '上海'), (2, '北京'),),
        widget=widgets.Select #select框
    )

7.2、views

from django.shortcuts import render, redirect
from .forms import MyForm
 
 
def index(request):
    if request.method == "GET":
        values = {'user': 'root', 'city': 2}
        obj = MyForm(values)   #通过键值对形式初始化数据
 
        return render(request, 'index.html', {'form': obj})
    elif request.method == "POST":
        return redirect('http://www.google.com')
    else:
        return redirect('http://www.google.com')

7.3、HTML

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <p>{{ form.user }} {{ form.user.errors }}</p>
    <p>{{ form.city }} {{ form.city.errors }}</p>
 
    <input type="submit"/>
</form>

参考文档:https://www.cnblogs.com/wupeiqi/articles/6144178.html#

8、django序列化

8.1、views

from django.shortcuts import render,HttpResponse
from app01 import models
import json
def serial(request):
    # user_list = models.UserInfo.objects.all()

    return render(request,'serial.html')
"""
方式一:不推荐
def get_data(request):
    user_list = models.UserInfo.objects.all()
    return render(request,'get_data.html',{'user_list':user_list})
"""

#方式二
def get_data(request):
    from django.core import serializers  #django自身提供的序列化,对queryset进行序列化
    ret = {'status': True,'data':None}
    try:
        #如果queryset里面时一个一个对象,可以使用如下方式
        #user_list = models.UserInfo.objects.all()
        ##user_list ==>queryset [obj,obj,obj]
        #ret['data'] = serializers.serialize("json",user_list)
        #前端需要反序列化
        # // var
        # v = JSON.parse(arg.data); // 反序列化
        # // console.log(v);

        #方式二
        # user_list = models.UserInfo.objects.all().values('id','username')
        #将queryset转换为python的基本类型list
        # ret['data'] = list(user_list)
        #前端console.log(v)

        #方式三:values_list  ==>元组
        user_list = models.UserInfo.objects.all().values_list('id','username')
        ret['data'] = list(user_list)

    except Exception as e:
        ret['status'] = False
    result = json.dumps(ret)     ##TypeError: Object of type QuerySet is not JSON serializable
    # result = serializers.serialize("json",ret)  #AttributeError: 'str' object has no attribute '_meta'
    print(result)
    #{"status": true, "data": [[1, "dootech"], [2, "bbbbbbbbbb"], [3, "dadad"]]}

    return HttpResponse(result)

8.2、html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table id="tb">

    </table>
<script src="/static/jquery-3.1.1.js"></script>
<script>
    $(function(){
        initData();
    })

    function initData(){
        $.ajax({
            url: '/get_data/',
            type: 'GET',
            dataType: 'JSON',
            success:function(arg){
                {#console.log(arg);#}
                {#$('#tb').append(arg)#}
                if(arg.status){
                    console.log(arg.data);
                    //var v = JSON.parse(arg.data);  //反序列化
                    //console.log(v);

                }
            }
        })
    }
</script>
</body>
</html>
参考文档:https://www.cnblogs.com/wupeiqi/articles/5246483.html#

posted @ 2019-09-28 09:41  运维人在路上  阅读(486)  评论(0编辑  收藏  举报