博客
关于我
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/

    你可能感兴趣的文章
    Prometheus监控教程:安装部署
    查看>>
    Prometheus监控教程:配置介绍
    查看>>
    Pytorch中tqdm进度条的使用
    查看>>
    Prometheus(2):SpringBoot 2.X集成Prometheus
    查看>>
    Promise 原理解析与实现(遵循Promise/A+规范)
    查看>>
    PyTorch:传递 numpy 数组进行权重初始化
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 8 Save and Load Model
    查看>>
    promise.all是并发执行吗_攻破面试灵魂拷问,解读Java并发编程的艺术,本文带你深入l理解...
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 7 Optimization
    查看>>
    promise总结
    查看>>
    Propel项目改为基于TensorFlow.js
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 6 Autograd
    查看>>
    properties出现中文乱码解决方法(万能)
    查看>>
    Property 'submit' of object #<HTMLFormElement> is not a function
    查看>>
    property--staticmethod--classmethod
    查看>>
    propertyGrid
    查看>>
    propertyPlaceholderConfigurer读取配置文件
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 5 Build Model
    查看>>
    proteus三输入与非门名字_proteus 元件名称对照表
    查看>>
    Protobuf - 语法、字段使用规则、注意事项
    查看>>