Django--form基础
一、Django--form功能
用户提交数据验证
生成html标签
二、基础实例
需求
利用Django的form功能,接收用户注册信息。
urls.py
1 2 3 4 5 | from app01 import views urlpatterns = [ url(r '^admin/' , admin.site.urls), url(r '^user_list/' , views.user_list), ] |
app01/views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from django import forms class UserInfo(forms.Form): #创建类,必须继承自forms.Form email = forms.EmailField() #生成字段,自动创建标签 host = forms.CharField() port = forms.CharField() mobile = forms.CharField() def user_list(request): obj = UserInfo() if request.method = = "POST" : user_input_obj = UserInfo(request.POST) #将所有提交的数据封装到自定义form类的对象里 if user_input_obj.is_valid(): #判断提交的数据是否合法,有一个错误就是false data = user_input_obj.clean() #如果合法,打印所有信息 print data else : #如果不合法,将所有错误信息返回给页面,到页面后再利用变量的取值输出每个错误 error_msg = user_input_obj.errors #默认是as_ul()列表形式,可以改成as_json()和as_data()。【看d18-16视频】 return render(request, 'user_list.html' ,{ 'obj' :user_input_obj, 'errors' :error_msg}) return render(request, 'user_list.html' ,{ 'obj' :obj}) |
templates/user_list.py
1 2 3 4 5 6 7 8 9 | < body > < form action = "/user_list/" method = "post" > < p >主机:{{ obj.host }}< span >{{ errors.host }}</ span ></ p > <!--obj是创建form类的实例化对象,host是变量--> < p >端口:{{ obj.port }}< span >{{ errors.port }}</ span ></ p > < p >邮箱:{{ obj.email }}< span >{{ errors.email }}</ span ></ p > < p >手机:{{ obj.mobile }}< span >{{ errors.mobile }}</ span ></ p > < input type = "submit" value = "submit" > </ form > </ body > |
browser
三、定制化
1、根据正则判断输入
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import re 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( '手机号码格式错误' ) from django import forms class UserInfo(forms.Form): email = forms.EmailField() host = forms.CharField() port = forms.CharField() mobile = forms.CharField( validators = [mobile_validate, ], #根据正则判断 ) |
browser
2、select类型
views.py
1 2 3 4 5 6 | class UserInfo(forms.Form): user_type_choice = ( #先设定选项 ( 0 , u '普通用户' ), ( 1 , u '高级用户' ), ) user_type = forms.IntegerField(widget = forms.widgets.Select(choices = user_type_choice,attrs = { 'class' : "form-control" })) |
user_list.html
1 | < p >用户类型:{{ obj.user_type }}< span >{{ errors.user_type }}</ span ></ p > |
browser
3、其它设置
views.py
1 2 3 4 5 6 | class UserInfo(forms.Form): email=forms.EmailField( required=False, error_messages={ 'required' : u '邮箱不能为空' , 'invalid' : u '邮箱格式错误' }, widget=forms.TextInput(attrs={ 'class' : "form-control" , 'placeholder' : u '邮箱' }) ) |