#功能: # - 對用戶提交的數據進行驗證 # - 保留上次輸入內容 # - 生成HTML標籤
#建立Form類時,主要涉及到 字段 和 插件 # - 字段用於對用戶請求數據的驗證 # - 插件用於自動生成HTML
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內容後綴 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) 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類型 ...
1. 驗證html
#required #error_messages
class TestForm(Form): t1 = fields.CharField( required=True, max_length=8, min_length=2, error_messages={ "required":"不能爲空", "max_length":"太長", "min_length":"過短", } ) t2 = fields.IntegerField( min_value=10, max_value=1000, error_messages={ "required": "t2不能爲空", "invalid":"t2格式錯誤,必須是數字", "min_value":"必須大於10", "max_value":"必須小於1000", } ) t3 = fields.EmailField( error_messages={ "required": "t3不能爲空", "invalid": "t3格式錯誤,必須是郵箱格式", } ) t4 = fields.URLField() t5 = fields.SlugField() t6 = fields.GenericIPAddressField() t7 = fields.DateField() t8 = fields.DateTimeField() t9 = fields.RegexField("139\d+")
2. 生成html標籤前端
Field widget=None, HTML插件 label=None, 用於生成Label標籤或顯示內容 initial=None, 初始值 help_text='', 幫助信息(在標籤旁邊顯示) show_hidden_initial=False, 是否在當前插件後面再加一個隱藏的且具備默認值的插件(可用於檢驗兩次輸入是否一直) disabled=False, 是否能夠編輯 label_suffix=None Label內容後綴
############# views.py class TestForm(Form): t1 = fields.CharField( label="用戶名", label_suffix=":", #label內容後綴 前端寫obj.as_p才顯示 help_text="....", #提供幫助信息 initial="666", required=True, max_length=8, min_length=2, error_messages={ "required":"不能爲空", "max_length":"太長", "min_length":"過短", } ) def test(request): if request.method == "GET": obj = TestForm() return render(request,"test.html",{"obj":obj}) else: obj = TestForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: print(obj.errors) return render(request, "test.html") #前端 html 兩種方式顯示 #方式一: <form action="/test/" method="POST"> {% csrf_token %} {{ obj.t1.label }}{{ obj.t1.label_suffix }} {{ obj.t1 }}{{ obj.t1.help_text }} <input type="submit" value="提交"> </form> 方式二: <form action="/test/" method="POST"> {% csrf_token %} {{ obj.as_p }} <input type="submit" value="提交"> </form>
保留上次提交的內容:python
#obj = TestForm() #obj.t1 <input type="text" name=t1/> #obj = TestForm(request.POST) #obj.t2 <input type="text" name=t1 values="xxx" />
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/test/" method="POST" novalidate> {% csrf_token %} <p> {{ obj.t1 }}{{ obj.errors.t1.0 }} </p> <p> {{ obj.t2 }}{{ obj.errors.t2.0 }} </p> <input type="submit" value="提交"> </form> </body> </html>
from django.shortcuts import render,HttpResponse # Create your views here. from django.forms import Form,fields class TestForm(Form): t1 = fields.CharField(required=True,max_length=8,min_length=2, error_messages={ "required":"不能爲空", "max_length":"太長", "min_length":"過短", } ) t2 = fields.EmailField() def test(request): if request.method == "GET": obj = TestForm() #沒有參數,至關於去建立 #input等標籤,<input type="text" name="t2">,沒有value return render(request,"test.html",{"obj":obj}) else: obj = TestForm(request.POST) #取到數據 if obj.is_valid(): print(obj.cleaned_data) else: print(obj.errors) return render(request, "test.html",{"obj":obj}) #<input type="text" name="t2" value="xx">
#obj = xxForm({"title":"全棧一期"}) #默認第一個參數是data,要驗證 #obj = xxForm(data = {"title":"全棧一期"}) #參數data要驗證,有錯誤前端會提示 obj.errors.title.0 #obj = xxForm(request.POST) #request.POST默認是data = request.POST #obj = xxForm(initial = {"title":"全棧一期"}) #initial #不驗證
#單選 cls_id = fields.IntegerField( # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')]) widget=widgets.Select(choices=models.Classes.objects.values_list('id','title')) ) cls_id = fields.ChoiceField( choices=models.Classes.objects.values_list('id','title'), widget=widgets.Select(attrs={'class': 'form-control'}) ) obj = FooForm({'cls_id':1}) #多選 xx = fields.MultipleChoiceField( choices=models.Classes.objects.values_list('id','title'), widget=widgets.SelectMultiple ) obj = FooForm({'cls_id':[1,2,3]})
1. 修復編輯老師時,不能實時更新班級列表 jquery
方式一(推薦): git
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class TeacherForm(Form): tname = fields.CharField(min_length=2) xx = fields.MultipleChoiceField( # choices=models.Classes.objects.values_list("id","title"), widget=widgets.SelectMultiple ) def __init__(self,*args,**kwargs): super(TeacherForm,self).__init__(*args,**kwargs) self.fields["xx"].choices =models.Classes.objects.values_list("id","title")
方式二:ajax
from django import forms from django.forms import fields from django.forms import widgets from django.forms import models as form_model from django.core.exceptions import ValidationError from django.core.validators import RegexValidator class TeacherForm(Form): tname = fields.CharField(min_length=2) xx = form_model.ModelMultipleChoiceField(queryset=models.Classes.objects.all()) # xx = form_model.ModelChoiceField(queryset=models.Classes.objects.all()) class Classes(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title
class TestForm(Form): t1 = fields.CharField( widget=widgets.Textarea(attrs={}) ) #單選框 t2 = fields.CharField( widget=widgets.CheckboxInput ) #複選框 t3 = fields.MultipleChoiceField( choices=[(1,"籃球"),(2,"足球"),(3,"溜溜球")], widget=widgets.CheckboxSelectMultiple ) def test(request): obj = TestForm(initial={"t3":[2,3]}) return render(request,"test.html",{"obj":obj})
class TestForm(Form): t4 = fields.MultipleChoiceField( choices=[(1,"籃球"),(2,"足球"),(3,"溜溜球")], widget=widgets.RadioSelect ) t5 = fields.ChoiceField( choices=[(1,"籃球"),(2,"足球"),(3,"溜溜球")], widget=widgets.RadioSelect ) def test(request): obj = TestForm() return render(request,"test.html",{"obj":obj})
提交方式: - Form提交(刷新,失去上次內容) - Ajax提交(不刷新,保留上次內容)
a. form提交
正則表達式
urlpatterns = [ url(r'^login/', views.login), ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form method="POST" action="/login/"> {% csrf_token %} <p> 用戶:<input type="text" name="username"/>{{ obj.errors.username.0 }} </p> <p> 密碼:<input type="password" name="password"/>{{ obj.errors.password.0 }} </p> <input type="submit" value="提交" />{{ msg }} </form> </body> </html>
from django.shortcuts import render,HttpResponse,redirect from django.forms import Form from django.forms import fields class LoginForm(Form): # 正則驗證: 不能爲空,6-18 username = fields.CharField( max_length=18, min_length=6, required=True, error_messages={ 'required': '用戶名不能爲空', 'min_length': '過短了', 'max_length': '太長了', } ) # 正則驗證: 不能爲空,16+ password = fields.CharField(min_length=16,required=True) # email = fields.EmailField() # email = fields.GenericIPAddressField() # email = fields.IntegerField() def login(request): if request.method == "GET": return render(request,'login.html') else: obj = LoginForm(request.POST) if obj.is_valid(): # 用戶輸入格式正確 print(obj.cleaned_data) # 字典類型 return redirect('http://www.baidu.com') else: # 用戶輸入格式錯誤 return render(request,'login.html',{'obj':obj}) Views.py
b. Ajax提交數據庫
urlpatterns = [ url(r'^ajax_login', views.ajax_login), ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>用戶登陸</h3> <form id="f1"> {% csrf_token %} <p> <input type="text" name="user">{{ obj.errors.user.0 }} </p> <p> <input type="password" name="pwd">{{ obj.errors.pwd.0 }} </p> <a onclick="Ajax_sublit()">提交</a> </form> <script src="/static/jquery-3.2.1.js"></script> <script> function Ajax_sublit() { $(".c1").remove(); $.ajax({ url:"/ajax_login/", type:"POST", data:$("#f1").serialize(), dataType:"JSON", success:function (arg) { console.log(arg); if(arg.staus){ }else { $.each(arg.msg,function (index,value) { console.log(index,value); var tag = document.createElement("span"); {# var tag = $("<span>");#} tag.innerHTML = value[0]; {# tag.HTML(value[0]);#} tag.className = "c1"; $("#f1").find('input[name="'+ index +'"]').after(tag); }) } } }) } </script> </body> </html>
from django.shortcuts import render,HttpResponse # Create your views here. from django.forms import Form,fields class LoginForm(Form): user = fields.CharField(required=True) pwd = fields.CharField(min_length=6) def ajax_login(request): import json ret = {"status":True,"msg":None} if request.method == "GET": return render(request,"login.html") else: obj = LoginForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: ret["status"] = False ret["msg"] = obj.errors v = json.dumps(ret) return HttpResponse(v)