博客
关于我
Django Form组件
阅读量:616 次
发布时间:2019-03-12

本文共 5245 字,大约阅读时间需要 17 分钟。

使用Form组件验证

views

from django.shortcuts import render, HttpResponsefrom django import formsclass LoginForm(forms.Form):    name = forms.CharField(        label='用户名',        initial='陌生人',        strip=True,        error_messages={            'required': '用户名不能为空',        }    )    password = forms.CharField(        label='密码',        min_length=6,        widget=forms.PasswordInput(render_value=True),        error_messages={            'required': '密码不能为空',            'min_length': '密码不能小于6位',        }    )    gender = forms.ChoiceField(        choices=[(1, '男'), (2, '女'), (3, '保密')],        label='性别',        initial=3,        widget=forms.RadioSelect(),        error_messages={            'required': '请选择性别',        }    )    hobby = forms.ChoiceField(        label='爱好',        widget=forms.Select(),        choices=((1, '篮球'), (2, '足球'), (3, '乒乓球')),        initial=2,    )    hobby2 = forms.MultipleChoiceField(        label='爱好2',        choices=((1, '摩托车'), (2, '汽车'), (3, '游艇')),        initial=[1, 3],        widget=forms.SelectMultiple(),    )    keep = forms.ChoiceField(        label='是否记住密码',        initial='checked',        widget=forms.CheckboxInput(),    )    city = forms.ChoiceField(        label='居住城市',        choices=[(1, '北京'), (2, '天津'), (3, '上海'), (4, '武汉')],        initial=4,        widget=forms.Select(),    )def login(request):    form_obj = LoginForm()    if request.method == 'POST':        form_obj = LoginForm(request.POST)        if form_obj.is_valid():            pass    return render(request, 'app/login.html', {'form_obj': form_obj})

templates

{% csrf_token %}

{{ form_obj.name }} {{ form_obj.name.errors.0 }}

{{ form_obj.password }} {{ form_obj.password.errors.0 }}

{{ form_obj.gender }} {{ form_obj.gender.errors.0 }}

{{ form_obj.hobby }} {{ form_obj.hobby.errors.0 }}

{{ form_obj.hobby2 }} {{ form_obj.hobby2.errors.0 }}

{{ form_obj.keep }} {{ form_obj.keep.errors.0 }}

{{ form_obj.city }} {{ form_obj.city.errors.0 }}

常用Form组件内置字段

Field的常用属性包括:

  • required=True:字段是否必填,默认为真
  • widget=None:绑定特定的HTML插件
  • label=None:用于生成Label标签或显示内容
  • initial=None:字段初始值
  • help_text='':帮助信息(显示在标签旁边)
  • error_messages=None:定义错误信息
  • validators=[]:自定义验证规则
  • localize=False:是否支持本地化
  • disabled=False:是否可用
  • label_suffix=None:Label内容后缀

如需扩展,其它字段可根据需求添加,例如:

  • CharField:最大长度、最小长度、是否移除空白
  • IntegerField:最大值、最小值
  • RegexField:自定义正则表达式
  • ChoiceField:枚举类型选择

字段校验

  • **RegexValidator**验证器:
  • from django.core.validators import RegexValidatorno = forms.CharField(    label='员工编号',    validators=[        RegexValidator(r'^[0-9]+', '请输入数字'),        RegexValidator('^110[0-9]+$', '请以110开头')    ])
    1. 自定义函数验证
    2. import redef mobile_validate(value):    mobile_re = re.compile(r'^1[2356789]{1}[0-9]{9}$')    if not mobile_re.match(value):        raise ValidationError('手机号格式错误')class LoginForm(forms.Form):    mobile = forms.CharField(        label='手机号',        validators=[mobile_validate, ],        error_messages={            'required': '手机号不能为空',        }    )

      Hook方法

    3. 局部钩子
    4. class LoginForm(forms.Form):    description = forms.CharField(        label='内容描述',        initial='暂无描述',        min_length=4,        error_messages={            'required': '不能为空',            'invalid': '格式错误',            'min_length': '最少评论4个字'        }    )    def clean_description(self):        value = self.cleaned_data.get('description')        if '666' in value:            raise ValidationError('请不要喊666')        else:            return value
      1. 全局钩子
      2. class LoginForm(forms.Form):    password = forms.CharField(        label='密码',        min_length=6,        widget=forms.PasswordInput(),        error_messages={            'required': '密码不能为空',            'min_length': '密码不能小于6位'        }    )    repassword = forms.CharField(        label='请再次输入密码',        min_length=6,        widget=forms.PasswordInput(),        error_messages={            'required': '密码不能为空',            'min_length': '密码不能小于6位'        }    )    def clean(self):        password_value = self.cleaned_data.get('password')        repassword_value = self.cleaned_data.get('repassword')        if password_value == repassword_value:            return self.cleaned_data        else:            self.add_error('repassword', '两次密码不一致')

        源码分析

    转载地址:http://vwhxz.baihongyu.com/

    你可能感兴趣的文章
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node exporter完整版
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node 裁切图片的方法
    查看>>
    Node+Express连接mysql实现增删改查
    查看>>
    node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
    查看>>
    Node-RED中Button按钮组件和TextInput文字输入组件的使用
    查看>>
    Node-RED中Switch开关和Dropdown选择组件的使用
    查看>>