Django學習手冊 - Form 插件
阿新 • • 發佈:2018-11-16
show pos class 編輯 p標簽 image local 保存 sage
""" 核心:
from django import forms
from django.forms import fields
from django.forms import widgets
class table_name(forms.Form) 自定義字段名 = fields.字段數據類型(字段參數)
字段數據類型: 基本字段: fields.CharField() #字符串類型 fields.IntegerField() #整型類型 fields.FloatField() #浮點類型 fields.EmailField() #郵箱 fields.DecimalField() #自定義浮點類型 自參數: max_digits=20 #總長度 decimal_places=20 #小數長度 #文件類型 #html form上傳時,enctype="multipart/form-data" ,views 中 request.FILES fields.ImageField() #圖片上傳按鈕。需要pillow模塊 fields.filefield() #文件上傳選項 fields.filepathfiled() #對應一個(文件組成的下拉菜單)選擇,必須參數path=‘‘.選項為這個地址裏邊所有的文件。
可選參數recursive=True是否包含子文件夾裏的文件 #日期/時間 fields.DateField() #日期,格式:2015-09-01 fields.TimeField() #時間,格式:11:11 fields.DateTimeField() #日期時間,2000-01-01 11:11 fields.DurationField() #時間間隔,%d %H:%M:%S.%f #IP地址 fields.GenericIPAddressField() #ip地址類型 #選擇框 fields.booleanfield() #checkbox選擇框 fields.ChoiceField() #choice類型 單選框(返回的值為字符串) fields.MultipleChoiceField() #choice類型 多選框 多值為列表(返回的值為字符串) 自參數: choices=[(1,‘A‘),(2,‘B‘),(3,‘C‘)] fields.TypedChoiceField() #choice類型 單選框(返回的值可定制) fields.TypedMultipleChoiceField() #choice類型 多選框 多值為列表(返回的值可定制) 自參數: coerce = lambda x : int(x) choices=[(1,‘A‘),(2,‘B‘),(3,‘C‘)] #自定制 fields.RegexField() #自定義屬性 自參數: regx #自定義正則表達式 FORM 字段參數: required=True, #必填 max_length=20, #最大值 min_length=5, #最小值 error_messages="required":‘不能為空!‘}, #錯誤信息 label="用戶名" #標簽名 initial="請輸入用戶名" #默認值 show_hidden_initial=True/False #隱藏,且保存上次數據(檢測兩次輸入) validators=[] #自定制驗證規則 localsize=True/False #是否支持本地化 disabled =True/False #是否能編輯 widget #定制HTML插件 1.自定義顯示html type 2.設置參數屬性值 3.設置css樣式"""
示例:
from django import forms from django.forms import fields from django.forms import widgets class TestTorm(forms.Form): user = fields.CharField(required=True,#必填 error_messages={"required":‘不能為空!‘}, label="用戶名", ) age= fields.IntegerField(required=True, label="年齡", error_messages={ "required":‘不能為空!‘, "min_value":"太小了", ‘max_value‘:‘太老了‘ }, min_value=18, max_value=50) email = fields.EmailField(required=True,label="郵箱",error_messages={"required":‘不能為空!‘}) choice = [(1, ‘A‘), (2, ‘B‘), (3, ‘C‘)] aaa = fields.TypedChoiceField(choices=choice) # 通過widget 自定制方式 aab = fields.CharField(widget=widgets.Select()) # 通過__init__ 實時獲取數據庫的數據 傳遞給前端頁面 def __init__(self,*args,**kwargs): from app01 import models super(TestTorm,self).__init__(*args,**kwargs) self.fields[‘aab‘].widget.choices= models.Userinfo.objects.values_list(‘uid‘,‘uname‘) #實例化時,傳遞值 # obj = TestTorm(‘可以以字典方式設置默認值‘)
views 頁面:(導入TestTorm,然後實例化,然後將實例傳遞至前端)
from django.shortcuts import render,HttpResponse from app01.tests import TestTorm # Create your views here. def index(request): if request.method == ‘GET‘: obj = TestTorm() # obj = TestTorm(‘可以以字典方式設置默認值‘) return render(request, ‘index.html‘,{‘obj‘:obj}) else: obj = TestTorm(request.POST) return render(request, ‘index.html‘, {‘obj‘: obj})
obj = TestTorm(request.POST) 獲取前端提交的字段,驗證是否符合,不符合即 錯誤字段提示
前端頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> {#不同的生成方式一#} <form method="post" action="/index/" novalidate > {#novalidate 不加載 #} <li>{% csrf_token %}</li> <p>{{ obj.user.label }}{{ obj.user }}{{ obj.errors.user.0 }}</p> <p>{{ obj.age.label }}{{ obj.age }}{{ obj.errors.age.0 }}</p> <p>{{ obj.email.label }}{{ obj.email }}{{ obj.errors.email.0 }}</p> <p>{{ obj.aaa.label }}{{ obj.aaa }}{{ obj.errors.aaa.0 }}</p> <p>{{ obj.aab.label }}{{ obj.aab }}{{ obj.errors.aab.0 }}</p> <li><input type="submit" class="tijiao" value="提交"></li> </form> {#不同的生成方式:二 生成整表#} <form method="post" action="/index/" novalidate > {{ obj.as_p }} {#p標簽形式#} </form> <form method="post" action="/index/" novalidate > {{ obj.as_table }} {#table標簽形式#} </form> <form method="post" action="/index/" novalidate > {{ obj.as_ul }} {#ul標簽形式#} </form> </div> </body> </html>
自定制
以上要不滿足需求還可以自定制: widget 1.自定義顯示html type 2.設置參數屬性值 attr={‘class‘:‘classname‘} 3.設置css樣式 attr={‘study‘:‘classname‘} # 先導入這個模塊 from django.forms import widgets # 參數 格式 自定義字段名 = fields.字段數據類型(widget=widgets.插件(參數:attr={‘class‘:‘classname‘})) choice = [(1, ‘A‘), (2, ‘B‘), (3, ‘C‘)] aab = fields.CharField(widget=widgets.Select(choices=choice))
渲染問題
為什麽Django傳遞至前端的 字符串能正常渲染成HTML標簽,不是要加{{ | safe }} 才可以顯示的嗎?????
python 通過拼接字符串然後傳遞至前端頁面渲染成HTML標簽 前有學過在 {{text | safe }} 即可渲染 Django中可以:
from django.utils.safestring import mark_safe text = mark_safe(text) 再傳遞至前端也可以達到效果
Django學習手冊 - Form 插件