Form组件
Django的Form主要具有一下几大功能:
--生成HTML标签
--验证用户数据(显示错误信息)
--HTML Form提交保留上次提交数据
--初始化页面显示内容
1、内置字段(用于保存正则表达式-->对用户请求数据的验证)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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内容后缀 *注:继承field的字段 field里面的参数都可以用 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) *等同于CharField加上validators 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类型 ...
2、内置插件(用于自动生成HTML-->保留上次输入内容)
除了choice都是form写好的正则表达式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
* 插件用于生成HTML,所有的插件都可以用attrs={'class':'c1'}创建默认值 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
3、常用选择插件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<strong># 单radio,值为字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 单radio,值为字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.RadioSelect # ) <strong># 单select,值为字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.Select(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 单select,值为字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.Select # ) <strong># 多选select,值为列表</strong> # user = fields.MultipleChoiceField( # choices=((1,'上海'),(2,'北京'),), # initial=[1,], # widget=widgets.SelectMultiple # ) <strong># 单checkbox</strong> # user = fields.CharField( # widget=widgets.CheckboxInput() # ) <strong># 多选checkbox,值为列表</strong> # user = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, '上海'), (2, '北京'),), # widget=widgets.CheckboxSelectMultiple # )
4、表单验证(验证;保留上次内容)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app02', ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from app02 import views as v2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^f1.html$', v2.f1), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse from django import forms from django.forms import fields class F1Form(forms.Form): # 跟表单提交的name值一一对应进行验证 user = forms.CharField(error_messages={'required':'用户名不能为空'}) pwd = forms.CharField( max_length=12, min_length=6, error_messages={'required': '密码不能为空','min_length':'密码长度不能小于6位', 'max_length': '密码长度不能大于12位'} ) email = forms.EmailField(error_messages={'required':'用户名不能为空','invalid':'邮箱格式不正确'}) def f1(request): if request.method == "GET": obj = F1Form() return render(request,'f1.html',{'obj':obj}) elif request.method == "POST": # 获取用户所有数据 # 每条数据请求的验证 # 成功:获取所有的正确的信息 # 失败:显示错误信息 obj = F1Form(request.POST) result = obj.is_valid() # 进行验证 True/False if result: print(obj.cleaned_data) # 用户提交的正确信息 else: print(obj.errors.as_json) # 所有错误信息 obj.errors return render(request, 'f1.html',{'obj':obj}) # 传入obj
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/f1.html" method="POST" novalidate > <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> <input type="submit" value="提交" /> </form> </body> </html>
5、初始默认显示数据(示例)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/add_user/" 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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django import forms as dforms from django.forms import fields class UserForm(dforms.Form): username = fields.CharField() email = fields.EmailField()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render from django.shortcuts import 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(): models.UserInfo.objects.create(**obj.cleaned_data) #cleaned_data(字典格式)创建 return redirect('/users/') else: return render(request,'add_user.html',{'obj':obj}) def edit_user(request,nid): if request.method == "GET": data = models.UserInfo.objects.filter(id=nid).first() #根据id来获取当前的id的默认显示内容 obj = UserForm({'username':data.username,'email':data.email}) return render(request,'edit_user.html',{'obj':obj,'nid':nid}) else: obj = UserForm(request.POST) if obj.is_valid(): models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data) #cleaned_data(字典格式)更新 return redirect('/users/') else: return render(request,'edit_user.html',{'obj':obj,'nid':nid})
6、动态Select数据源实时更新(示例)
在使用选择标签时,需要注意choices的选项可以从数据库中获取,但是由于是静态字段(类变量) ***获取的值无法实时更新***,那么需要自定义构造方法从而达到此目的。
方法一:(推荐使用)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>23435</h1> <p>价格:{{ obj.price }}</p> <p>姓名{{ obj.user_id }}</p> <p>姓名{{ obj.user_id2 }}</p> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from django.contrib import admin from app01 import views as v2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^love/', v2.love), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render from django import forms from django.forms import fields from django.forms import widgets from app01 import models from django.forms.models import ModelChoiceField class LoveForm(forms.Form): price = fields.IntegerField() user_id = fields.IntegerField( # widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),]) widget=widgets.Select() #widget=widgets.Textarea(attrs={'class':'c1'}), # 定制样式: 变成长框输入,添加样式class=c1 ) user_id2 = ModelChoiceField( queryset=models.UserInfo.objects.all(), to_field_name='id' ) #自定义构造方法,实时刷新页面数据 def __init__(self,*args,**kwargs): # 拷贝所有的静态字段,复制给self.fields super(LoveForm,self).__init__(*args,**kwargs) self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id', 'username') self.fields['user_id2'].widget.choices = models.UserInfo.objects.values_list('id', 'username') def love(request): obj = LoveForm() return render(request,'love.html',{'obj':obj})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32)
方法二:(不推荐)
使用django提供的ModelChoiceField和ModelMultipChoiceField字段来实现
(这种django内置的方法不推荐使用,如果要在前端显示数据库中的用户名,需要依赖models中的__str__方法,而且一个class中只有一个__str__, 如果在有的场景中需要同时显示如id user, age等多个字段名时,这个方法就做不到)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from django.contrib import admin from app02 import views as v2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^love/', v2.love), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>有缘千里来相会</h1> <p>价格:{{ obj.price }}</p> <p>姑娘:{{ obj.user_id2 }}</p> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.forms.models import ModelChoiceField class LoveForm(forms.Form): price = fields.IntegerField() user_id2 = ModelChoiceField( queryset=models.UserInfo.objects.all(), to_field_name='id' )
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32) def __str__(self): return self.username # 注意:依赖models中的str方法
7、Ajax提交验证(验证;无需上次内容)
①返回HttpResponse
②前端:跳转或错误信息
如果想要ajax提交数据到django后台,对页面进行跳转,需要在ajax 中进行跳转,在后台进行跳转不生效.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm"> {% csrf_token %} <p>用户:<input type="text" name="username"/></p> <p>密码:<input type="password" name="password"/></p> <p><input type="button" id="btn" value="Ajax提交"></p> </form> <script src="/static/jquery-1.12.4.js"></script> <script> $(function () { $('#btn').click(function () { $.ajax({ url:'/login/', type:'POST', data:$('#fm').serialize(), success:function (arg) { console.log(arg) arg = JSON.parse(arg) console.log(arg) console.log(arg['error']['username'][0]) },error:function () { } }) }) }) </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import json from app01.forms import LoginForm def login(request): if request.method == "GET": return render(request, 'login.html') elif request.method == "POST": data = {'status':True,'error':None,'data':None} obj = LoginForm(request.POST) result = obj.is_valid() if result: print(obj.cleaned_data) else: from django.forms.utils import ErrorDict print(type(obj.errors)) #整体的错误信息打印 # < class 'django.forms.utils.ErrorDict'> data['error'] = obj.errors return HttpResponse(json.dumps(data)) # 传入obj
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django import forms from django.forms import fields from django.forms import widgets from app01 import models class LoginForm(forms.Form): username = fields.CharField() password = fields.CharField( max_length=20, min_length=12, )
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import json from django.core.exceptions import ValidationError class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, ValidationError): return {'code':field.code,'messages':field.messages} else: return json.JSONEncoder.default(self, field) from app01.forms import LoginForm def login(request): ---snip--- else: print(type(obj.errors.as_data())) #as_data虽然变成了字典,但是也不能直接dump # <class 'dict'> print(obj.errors.as_data()) #里面包含了ValidationError类型序列化会报错 # 'password': [ValidationError(['This field is required.'])], 'username': [ # ValidationError(['This field is required.'])]} data['error'] = obj.errors.as_data() data = json.dumps(data, cls=JsonCustomEncoder) #自定义JsonCustomEncoder方法序列化 return HttpResponse(json.dumps(data)) # 传入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import json from app01.forms import LoginForm def login(request): ---snip--- else: print(type(obj.errors.as_json())) #整体的错误信息打印 # <class 'str'> data['error'] = obj.errors.as_json() #把ErrorDict格式的obj.error转换为字符串格式 return HttpResponse(json.dumps(data)) # 传入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
浏览器: {"data": null, "status": true, "error": {"password": ["This field is required."], "username": ["This field is required."]}} Object {data: null, status: true, error: Object}data: nullerror: Objectstatus: true__proto__: Object This field is required.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@html_safe @python_2_unicode_compatible class ErrorDict(dict): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ def as_data(self): return {f: e.as_data() for f, e in self.items()} def as_json(self, escape_html=False): return json.dumps({f: e.get_json_data(escape_html) for f, e in self.items()}) def as_ul(self): if not self: return '' return format_html( '<ul class="errorlist">{}</ul>', format_html_join('', '<li>{}{}</li>', ((k, force_text(v)) for k, v in self.items())) ) def as_text(self): output = [] for field, errors in self.items(): output.append('* %s' % field) output.append(' '.join(' * %s' % e for e in errors)) return ' '.join(output) def __str__(self): return self.as_ul()
ErrorDict不是Dict的格式,无法用json.dumps进行序列化。
①用as_json()把ErrorDict转换为字符串然后传入data字典
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#处理文件: import json from app01.forms import LoginForm def login(request): ---snip--- else: print(type(obj.errors.as_json())) #整体的错误信息打印 # <class 'str'> data['error'] = obj.errors.as_json() #把ErrorDict格式的obj.error转换为字符串格式 return HttpResponse(json.dumps(data)) # 传入 #浏览器打印: {"status": true, "data": null, "error": "{"username": [{"code": "required", "message": "This field is required."}], "password": [{"code": "required", "message": "This field is required."}]}"} Object {status: true, data: null, error: "{"username": [{"code": "required", "message": "Thi…equired", "message": "This field is required."}]}"} data: null error: "{"username": [{"code": "required", "message": "This field is required."}], "password": [{"code": "required", "message": "This field is required."}]}" status: true #从上面可看到error打印出来的格式还是字符串,由于之前用as_json进行过一次序列化,json.dumps后又进行一次序列化;进行了两次序列化,所以反序列化时也需要两次
②用as_data()通过自定制json方法进行序列化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#处理文件: import json from django.core.exceptions import ValidationError class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, ValidationError): return {'code':field.code,'messages':field.messages} else: return json.JSONEncoder.default(self, field) from app01.forms import LoginForm def login(request): ---snip--- else: print(type(obj.errors.as_data())) #as_data虽然变成了字典,但是也不能直接dump # <class 'dict'> print(obj.errors.as_data()) #里面包含了ValidationError类型序列化会报错 # 'password': [ValidationError(['This field is required.'])], 'username': [ # ValidationError(['This field is required.'])]} data['error'] = obj.errors.as_data() data = json.dumps(data, cls=JsonCustomEncoder) #自定义JsonCustomEncoder方法序列化 return HttpResponse(json.dumps(data)) # 传入 #补充:由于json.dumps时无法处理datetime日期,所以可以通过自定义处理器来做扩展,如: #json自定制序列化方法 import json from datetime import date from datetime import datetime class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return field.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field, date): return field.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, field) v = {'k':123,'k1':datetime.now()} ds = json.dumps(v, cls=JsonCustomEncoder)
③serializers对QuerySet类型数据序列化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from app01 import models from django.core import serializers def index(request): v = models.User.objects.all() #QuerySet类型 # print(v) # <QuerySet[{'pwd': '123', 'user': 'root'}]> # json.dumps(v) #直接dumps会报错 data = serializers.serialize("json", v) #serializers方法 print(type(data)) # [{"model": "app01.user", "pk": 1, "fields": {"user": "root", "pwd": "123"}},] # < class 'str'> #类型 return HttpResponse('OK')
④QuerySet类型列表、字典序列化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from app01 import models def index(request): v = models.User.objects.values_list('user','pwd') #QuerySet类型 print(v) # < QuerySet[('root', '123')] > # json.dumps(v) #直接dumps会报错 data = list(v) json.dumps(data) return HttpResponse('OK') #如果values()取出来的值包含时间类型或其他,则依然不能进行dumps,需要跟之前自定制序列化方法结合起来使用
#Form组件扩展
①简单扩展(利用Form组件自带的正则扩展:)
a. 方式一
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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( error_messages={'invalid': '...'}, #错误提示 validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator
b. 方式二
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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. 单字段
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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. 整体错误验证
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
c、_post_clean 支持自定制方法(但不常用)