Form验证随笔 | Django
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Form验证随笔 | Django相关的知识,希望对你有一定的参考价值。
from django.shortcuts import render from app01.dadforms import DetailForm, VerifyForm def index(request): # 创建表单对象 detail_form = DetailForm(request.POST) # 验证输入表单数据 detail_form.is_valid() # 打印输入的正确数据 print(detail_form.clean()) return render(request, ‘index.html‘, locals()) def field_verified(request): if request.method == ‘GET‘: # 创建表单对象 verify_form = VerifyForm() return render(request, ‘verify.html‘, locals()) elif request.method == ‘POST‘: print(‘我是post方法‘) # 创建表单对象 verify_form = VerifyForm(request.POST, request.FILES) # 验证字段 verify_form.is_valid() # 打印正确字段 print(verify_form.clean()) print(verify_form.errors.as_json()) # errors = verify_form.errors return render(request, ‘verify.html‘, locals())
from django import forms from django.forms import fields # 导入插件模块,以自定义input标签 from django.forms import widgets class DetailForm(forms.Form): """1.forms中的__init__方法引入了fields等模块的内容, 所以,可以这么写:forms.CharField()""" # 用户名验证 user = fields.CharField( # widget=widgets.PasswordInput widget=widgets.TextInput(attrs={ ‘class‘:‘c1‘, ‘id‘:‘p‘, # 默认显示值 ‘placeholder‘:‘用户名‘ }) # 2.TextInput()文本输入框有一个attr方法,可以给input框添加属性; ) # 3.选项框 # sex = fields.ChoiceField( # choices=[ # (1, ‘男‘), # (2, ‘女‘) # ] # ) # 4.通过CharField()重现选项框,通过字段指定插件 sex = fields.CharField( widget = widgets.Select( choices=[ (1, ‘男‘), (2, ‘女‘) ] ) ) # 表单的作用:1.验证;2.生成html标签;3.数据转换; # 内部会对字符串做一个类型转换,转换成数字; score = fields.IntegerField() addr = fields.CharField( widget = widgets.Radioselect( choices=[ (1, ‘上海‘), (2, ‘温州‘) ] ) ) # ---------------------------- 字段验证 from django.core.validators import RegexValidator class VerifyForm(forms.Form): """ required=True, widget=None, label=None, initial=None, help_text=‘‘, error_messages=None, show_hidden_initial=False, validators=[], localize=False, label_suffix=None(label后缀符) """ # CharField()中__init__下有长度,以及是否取出空白的参数;(strip=True) # 而且继承Field()中的所有初始字段; user_name = fields.CharField( max_length=6, min_length=6, # 1.默认必填,False表示可以为空; required=True, # 2.设置默认值 initial=‘大山的姑娘‘, # 3.自定义验证规则 validators=[RegexValidator(r‘159[0-9]+$‘, ‘aaaaaaa‘, code=‘d1‘), RegexValidator(r‘^[0-9]+$‘, ‘bbbbbbb‘, code=‘d2‘)], # 4.错误信息,error_messages优先级比自定义规则的验证错误信息要高,会覆盖上面的; # 如果自定义验证有多个规则,可以通过RegexValidator里的第3个参数code指定显示验证信息; # 错误信息里,默认两个参数required和invalid(必须,格式); # 还有max_length等,前面加什么参数,code就是什么; error_messages={‘required‘: ‘不能为空‘, ‘d1‘: ‘1111111‘, ‘d2‘:‘22222222‘, ‘max_length‘: ‘too long‘}, # label,HTML中需要添加{{表单对象.label}} label=‘名字‘, label_suffix=‘::::‘, widget=widgets.TextInput(attrs={ ‘class‘: ‘a1‘, ‘placeholder‘: ‘山炮‘ }), # 是否可以编辑 disabled=True ) # 5.数字,有数值的限制; user_score = fields.IntegerField( max_value=20, required=True, initial=1, error_messages={‘required‘: ‘not blank‘, ‘max_value‘: ‘num too big‘} ) # 6.DecimalField继承IntegerField user_tax = fields.DecimalField( max_digits=4, # 总长度 decimal_places=2, # 小数位长度 # error_messages={‘invalid‘: ‘geshicuowu‘} ) # 7.正则表达式input框 user_tel = fields.RegexField( max_length=6, regex=(r‘159[0-9]+$‘), error_messages={‘invalid‘: ‘not true‘, ‘max_length‘:‘tooLong‘}, # [{"message": "not true", "code": "invalid"}] code表示错误类型 ), # 8.文件上传 # 注意两点: # 1.form表单中加入enctype="multipart/form-data" # 2.视图函数中创建表单对象时,obj = Myform(request.POST, request.FILES) user_file = fields.FileField( allow_empty_file=False, ), # 图片上传,ImageField继承FileField user_pic = fields.ImageField( allow_empty_file=False, ) # 9.ChoiceField选择框,默认是Select框; # TypedChoiceField() user_course = fields.TypedChoiceField( # 类型转化的匿名函数 coerce = lambda x: int(x), choices=[ (1, ‘语文‘), (2, ‘数学‘), (3, ‘未填写‘) ], initial=3, ) # 10.多选框MultipleChoiceField() user_class = fields.MultipleChoiceField( choices=[ (1, ‘09-03‘), (2, ‘09-02‘), (3, ‘09-01‘) ], initial=[2, 3], ) # 11.组合的字段验证 user_join = fields.ComboField( fields=[ fields.CharField(max_length=6), fields.EmailField(), ] ) # 12.多个框组合,0577-66666 user_local_phone = fields.SplitDateTimeField()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="verify.html" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ verify_form.user_name }}<br> {{ verify_form.user_score }}<br> {{ verify_form.user_tax }}<br> {{ verify_form.user_tel }}<br> {{ verify_form.user_file }}<br> {{ verify_form.user_pic }}<br> {{ verify_form.user_course }}<br> {{ verify_form.user_class }}<br> {{ verify_form.user_join }}<br> {{ verify_form.user_local_phone }}<br> <input type="submit", value="提交"> </form> </body> </html>
以上是关于Form验证随笔 | Django的主要内容,如果未能解决你的问题,请参考以下文章