• 【django】form


    form

    组件组要功能:

    • 生成HTML标签
    • 验证用户数据(显示错误信息)
    • HTML Form提交保留上次提交数据
    • 初始化页面显示内容

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

    ① 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类型
        ...   

     - 常用字段(重点)

    ChoiceField *****
    MultipleChoiceField
    CharField
    IntegerField
    DecimalField
    DateField
    DateTimeField
    EmailField
    GenericIPAddressField
    FileField
    
    RegexField

    ② 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
    # ) 

    2.表单验证

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    from app02 import views as v2
    
    urlpatterns = [
        url(r'^f1.html$', v2.f1),
    ]
    project/urls.py
    from django.shortcuts import render,HttpResponse,redirect
    from django import forms
    from django.forms import fields
    
    class F1From(forms.Form):
        user = fields.CharField( max_length=18,min_length=6,required=True,
            error_messages={
                'required': '用户不能为空',
                'max_length': '太长了',
                'min_length': '太短了',
                'invalid': '格式不正确',#格式不正确都是invalid
            }
        )
        pwd = fields.CharField( min_length=6, required=True,
            error_messages={
                'required' : '密码不能为空',
                'min_length': '太短了',
                'invalid' : '密码格式不正确',
            }
        )
        email = fields.EmailField(required=True,
            error_messages={
                'required' : '邮箱不能为空' ,
                'invalid' : '格式需为邮箱格式',
            }
        )
        age = fields.IntegerField( required=True,
            error_messages={
                'required': '年龄不能为空',
                'invalid' : '年龄需为数字',
            }
        )
    
    
    def f1(request):
        if request.method == "GET":
            obj = F1From()
            return render(request,'f1.html',{'obj':obj})
        else:
            # u = request.POST.get('user')
            # p = request.POST.get('pwd')
            # e = request.POST.get('email')
            # a = request.POST.get('age')
            # 1.检查是否为空
            # 2.检查格式是否正确
            # print(u,p,e,a)
    
            obj = F1From(request.POST)
            # 是否全部验证成功
            if obj.is_valid():
                #用户提交的数据
                print('验证成功',obj.cleaned_data)
                return redirect('http://www.baidu.com')
                # return render(request,'f1.html',{'obj':obj})
            else:
                print('验证失败',obj.errors)
            return render(request,'f1.html',{'obj':obj})
    app02/views.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form id="fm" action="/f1.html" method="POST">
            <P>用户: {{ obj.user }}{{ obj.errors.user.0 }}</P>{# 一个输入项可能包含多种格式错误,取第一个 .0 #}
            <P>密码: {{ obj.pwd }}{{ obj.errors.pwd.0 }}</P>
            <P>邮箱: {{ obj.email }}{{ obj.errors.email.0 }}</P>
            <P>年龄: {{ obj.age }}{{ obj.errors.age.0 }}</P>
            <input type="submit" value="form提交"/>
    
        </form>
    
    </body>
    </html>
    templates/f1.html

    效果展示:

              

    3、初始化默认值——form表单简单更改单表数据库数据(增,改,查)

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^users/', views.users),
        url(r'^add_user/', views.add_user),
        url(r'^edit_user-(d+)/', views.edit_user),
    ]
    project/urls.py
    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)
                # models.UserInfo.objects.create(
                #     username = obj.cleaned_data['username'],
                #     email = obj.cleaned_data['email'],
                # )
                # 后面一句可以直接代替上面语句
                models.UserInfo.objects.create(**obj.cleaned_data)
                return redirect('/users/')
            else:
                print('验证失败',obj.errors)
                return render(request,'add_user.html',{'obj':obj})
    
    def edit_user(request,nid):
        if request.method == 'GET':
            # p = request.GET.get('nid')
            data = models.UserInfo.objects.filter(id=nid).first()  # 拿到一个对象
            obj = UserForm({'username':data.username,'email':data.email})
            return render(request,'edit.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.html', {'obj': obj, 'nid': nid})
    app01/views.py
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:daly
    
    from django import forms as dforms
    from django.forms import fields
    
    class UserForm(dforms.Form):
        username = fields.CharField(
            required=True,
            min_length=6,
            error_messages={
                'required':"用户不能为空",
                'min_length':'太短了',
            }
        )
        email = fields.EmailField(
            required=True,
            error_messages={
                'required': "邮箱不能为空",
                'invalid':'邮箱格式错误',
            }
        )
    app01/forms.py
    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        username = models.CharField(max_length=32)
        email = models.EmailField(max_length=32)
    app01/models.py
    <!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>
    templates/users.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form method="post" action="/add_user/" 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>
    templates/add_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>
    templates/edit.html

    效果展示:

     4.动态更新实时数据

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

    方法一:(推荐)

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    from app02 import views as v2
    
    urlpatterns = [
        url(r'^love/', v2.love),
    ]
    project/urls.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>非诚勿扰</h1>
        <P>价格:{{ obj.prive }}</P>
        <P>人员:{{ obj.user_id }}</P>
    </body>
    </html>
    templates/love.html
    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        username = models.CharField(max_length=32)
        email = models.EmailField(max_length=32)
    app01/models.py
    from django.shortcuts import render
    from django import forms
    from django.forms import fields
    from django.forms import widgets
    
    from app01 import models
    class LoveForm(forms.Form):
        user_id = fields.IntegerField(
            widget=widgets.Select(
                # choices=[(0,'苹果'),(1,'梨子'),(2,'香蕉')],   #自己创建
                # choices= models.UserInfo.objects.values_list('id','username') #也可以从数据库取数据
            )
        )
        prive = fields.IntegerField()
    
        def __init__(self,*args,**kwargs):
            #拷贝所有静态字段,复制给self.fields (顺序:super->self.fields)
            super(LoveForm,self).__init__(*args,**kwargs)
            self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id','username')
    
    def love(requset):
        obj = LoveForm()
        return render(requset,'love.html',{'obj':obj})
    app02/views.py

    效果展示:

     方法二:(依赖于model中的__str__方法,多个slecte框不适用,耦合性太强)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>非诚勿扰</h1>
        <P>价格:{{ obj.prive }}</P>
        <P>人员:{{ obj.user_id }}</P>
        <P>人员:{{ obj.user_id2 }}</P>    <!--新增-->
    </body>
    </html>
    templates/love.html
    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        username = models.CharField(max_length=32)
        email = models.EmailField(max_length=32)
    
        def __str__(self):    #新增
            return self.username  #新增
    app01/models.py
    from django.shortcuts import render
    from django import forms
    from django.forms import fields
    from django.forms import widgets
    
    from app01 import models
    class LoveForm(forms.Form):
        user_id = fields.IntegerField(
            widget=widgets.Select(
                # choices=[(0,'苹果'),(1,'梨子'),(2,'香蕉')],   #自己创建
                # choices= models.UserInfo.objects.values_list('id','username') #也可以从数据库取数据
            )
        )
        prive = fields.IntegerField()
    
        from django.forms.models import ModelChoiceField    #新增
        user_id2 =ModelChoiceField(                        #新增
            queryset=models.UserInfo.objects.all(),         #新增
            to_field_name='id',                           #新增
        )                                                 #新增
    
        def __init__(self,*args,**kwargs):
            #拷贝所有静态字段,复制给self.fields (顺序:super->self.fields)
            super(LoveForm,self).__init__(*args,**kwargs)
            self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id','username')
    
    def love(requset):
        obj = LoveForm()
        return render(requset,'love.html',{'obj':obj})
    app02/views.py

    效果展示:

     5.Ajax提交验证(验证;无需上次内容)

     - 返回HttpResponse
     - 前端:跳转或错误信息

    如果想要ajax提交数据到django后台,对页面进行跳转,需要在ajax 中验证后进行跳转,在后台进行跳转不生效.

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    from app02 import views as v2
    
    urlpatterns = [
        url(r'^ajax/', v2.ajax),
    ]
    project/urls.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form id="fm" action="/ajax/" method="post" novalidate>
            {% csrf_token %}
            {{ obj.as_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 == ''){
                                window.location.href="http://www.baidu.com"
                            }
                            console.log(arg);
                        }
                    })
                })
            })
        </script>
    </body>
    </html>
    templates/ajax.html
    class AjaxForm(forms.Form):
        prive = fields.IntegerField()
        user_id = fields.IntegerField(
            widget=widgets.Select(
                choices=[(0,'苹果'),(1,'梨子'),(2,'香蕉')],
            )
        )
    
    def ajax(request):
        if request.method == 'GET':
            obj = AjaxForm()
            return render(request,'ajax.html',{'obj':obj})
        else:
            ret = {'status':'没钱','message':None}
            import json
            obj = AjaxForm(request.POST)
            # print(obj.cleaned_data)
            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))
                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))
    app02/views.py

    自定义验证规则(from组件扩展)

    方式一:

    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(
            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': '格式错误'})
    

    基于源码流程

    a. 单字段(clean_field)

    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,'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']
    

    b. 整体错误验证(clean_form)

    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('整体错误信息')
    		return self.cleaned_data                    
    

      

  • 相关阅读:
    从零开始搭建口袋妖怪管理系统(4)-借助webpack4.6工程化项目(上)
    JavaSE——装饰设计模式+简单加密解密工程
    MyEclipse和Eclipse区别与联系
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/dalyday/p/9106193.html
Copyright © 2020-2023  润新知