Django-Form
发布时间:2020-12-20 10:26:19 所属栏目:Python 来源:网络整理
导读:使用form实现注册功能 views.py 先定义好一个RegForm类: from django import forms # 按照Django form组件的要求自己写一个类 class RegForm(forms.Form): name = forms.CharField(label= " 用户名 " ) pwd = forms.CharField(label= " 密码 " ) 再写一个视
使用form实现注册功能
常用字段与插件
Django Form所有内置字段Field required=True,是否允许为空 widget=None,HTML插件 label=None,用于生成Label标签或显示内容 initial=None,初始值 help_text=‘‘,帮助信息(在标签旁边显示) error_messages=None,错误信息 {‘required‘: ‘不能为空‘,‘invalid‘: ‘格式错误‘} 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,最小值 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,最小长度 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,帮助提示 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类型 校验方式一: 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开头‘)],) 方式二: 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‘: ‘手机不能为空‘},‘placeholder‘: u‘手机号码‘})) email = fields.EmailField(required=False,error_messages={‘required‘: u‘邮箱不能为空‘,‘invalid‘: u‘邮箱格式错误‘},widget=widgets.TextInput(attrs={‘class‘: "form-control",‘placeholder‘: u‘邮箱‘})) 补充进阶
ModelFormform与model的终极结合。 class BookForm(forms.ModelForm): class Meta: model = models.Book fields = "__all__" labels = { "title": "书名","price": "价格" } widgets = { "password": forms.widgets.PasswordInput(attrs={"class": "c1"}),} ?class Meta:下常用参数: model = models.Student # 对应的Model中的类 fields = "__all__" # 字段,如果是__all__,就是表示列出所有的字段 exclude = None # 排除的字段 labels = None # 提示信息 help_texts = None # 帮助提示信息 widgets = None # 自定义插件 error_messages = None # 自定义错误信息 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 使用pytorch完成kaggle猫狗图像识别方式
- PackagesNotFoundError: The following packages are not a
- 如果您的代码隐藏运行infinte循环,如何获得响应式GUI? PyQ
- python – 在datetime,为什么`year`是一个属性,但`weekday(
- 为什么UnicodeEncodeError只在emacs的python shell中引发?
- Python打印“菱形”星号代码方法
- Python之路,Day14 - It's time for Django
- Python 语言
- python – 如何将两个二进制数合并为三进制数
- Python之路,Day9 - 异步IO\数据库\队列\缓存