Form
Form是Django提供的一個組件,主要作用有:生成頁面可用的HTML標籤、對用戶提交的數據進行校驗、保留上次輸入內容
生成標籤
視圖函數:
from django import forms
class User(forms.Form):
username = forms.CharField(
label="用戶名", # 自定義label名,默認爲當前字段名
widget=forms.TextInput(attrs={"class":"c1"}) # 設置插件和屬性 默認TextInput
# writers = forms.ModelChoiceField(queryset=models.Writer.object.all)
)
html:
<div>
{{ u_obj.username.label }} <!--拿到視圖類中設置的label值,作爲輸入框的提示-->
{{ u_obj.username }}<!--生成一個input標籤-->
</div>
常用插件與字段
initial
初始值,input框裏面的初始值
username = forms.CharField(
label="用戶名",
initial="abcd",)
error_messages
重新定義錯誤信息
sername = forms.CharField(
label="用戶名",
required=True, # 不能爲空
error_messages={
"required":"不能爲空",
}
)
password
密碼框
password = forms.CharField(
label="密碼",
widget=forms.widgets.PasswordInput(render_value=True)) # 通過render_value=True設置提交出錯後保留數據
radioSelect
sex = forms.ChoiceField(
label="性別",
choices=((1,"女"),(2,"男")), # 1:values值,女:顯示值
widget=forms.RadioSelect)
Select
sex = forms.ChoiceField(
label="性別",
choices=((1,"女"),(2,"男")),
widget=forms.Select, # 默認值 單選
widget=forms.SelectMultiple, # 多選
)
checkbox
hobby = forms.ChoiceField(
label="愛好",
choices=((1,"抽菸"),(2,"喝酒")),
widget=forms.CheckboxSelectMultiple, # 多選
widget=forms.CheckboxInput, # 單選
)
date
date = forms.DateField(
label = "日期",
widget=forms.DateInput(attrs={"type":"date"}) # 手動設置屬性
)
內置字段
Field
required=True, 是否允許爲空 默認爲True
widget=None, HTML插件
label=None, 用於生成Label標籤或顯示內容
initial=None, 初始值
help_text='', 幫助信息(在標籤旁邊顯示)
error_messages=None, 錯誤信息 {'required': '不能爲空', 'invalid': '格式錯誤'}
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類型
字段校驗
from django import forms
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空", # 定義錯誤信息提示
}
)
password = forms.CharField(
label="密碼",
widget=forms.widgets.PasswordInput,
)
def index(request):
if request.method=="GET":
u_obj = User()
return render(request, "index.html", {"u_obj": u_obj})
else:
u_obj = User(request.POST)
if u_obj.is_valid(): # 調用is_valid方法進行校驗
print(u_obj.cleaned_data) # 校驗通過的信息
else:
print(u_obj.errors) # 校驗失敗的信息
return render(request,"index.html",{"u_obj":u_obj})
<form action="" method="post" novalidate>
{% csrf_token %}
<div>
{{ u_obj.username.label }}
{{ u_obj.username }}
{{ u_obj.username.errors.0 }} <!--顯示錯誤信息-->
</div>
<div>
{{ u_obj.password.label }}
{{ u_obj.password }}
{{ u_obj.password.errors.0 }} <!--顯示錯誤信息-->
</div>
<input type="submit" >
</form>
正則校驗
from django import forms
from django.core.validators import RegexValidator
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空",
},
validators=[RegexValidator(r"^a","必須以a開頭"),RegexValidator(r"$c","必須以c結尾")]
)
自定義校驗函數
from django import forms
from django.core.exceptions import ValidationError
import re
def custom_verify(value):
verify_re = re.compile(r"^a")
if not verify_re.match(value):
raise ValidationError("必須以a開頭") # 提示的錯誤信息
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空",
},
validators=[custom_verify,]
)
局部鉤子
先執行username字段內的校驗,當校驗完成後,cleaned_data中值就存在了,然後再校驗局部鉤子,然後是password字段內的校驗
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空",
},
)
password = forms.CharField(
label="密碼",
widget=forms.widgets.PasswordInput, # 默認TextInput
)
def clean_username(self):
value = self.cleaned_data.get("username")
if "xx" in value:
raise ValidationError("不能含有xx")
else:
return value
全局鉤子
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空",
},
)
password = forms.CharField(
label="密碼",
widget=forms.widgets.PasswordInput, # 默認TextInput
)
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if "xx" in username and "xx" in password:
self.add_error("password","不能含有xx")
else:
return self.cleaned_data
批量添加屬性
class User(forms.Form):
username = forms.CharField(
label="用戶名",
required=True,
error_messages={
"required":"不能爲空",
},
)
password = forms.CharField(
label="密碼",
widget=forms.widgets.PasswordInput, )
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for name,field in self.fields.items():
field.widget.attrs.update({"class":"form-control"})
<form action="" method="post" novalidate>
{% csrf_token %}
{% for foo in u_obj %}
{{ foo.label }}
{{ foo }}
<span>{{ foo.errors.0 }}</span>
{% endfor %}
<input type="submit" >
</form>
ModelForm
form與model的結合,根據model中的字段轉換成對應的form字段,並且生成標籤等操作。
from django import forms
class BookModlForm(forms.ModelForm):
class Meta:
model = models.Books
fields = "__all__" # 指定將所有字段
exclued=[""]# 排除字段
labels = { # 分別指定labe名
"name": "書名",
"price": "價格",
"date": "日期",
"press": "出版社",
"writer": "作者",}
widgets = { # 指定類型
"date": forms.DateInput(attrs={"type": "date"})}
error_messages = { # 指定 錯誤信息
"name":{"required": "不能爲空",},
"price":{"required": "不能爲空",},
"date":{"required": "不能爲空",},
"press":{"required": "不能爲空",},
"writer":{"required": "不能爲空",},}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({"class": "form-control"}) # 統一設置樣式
# 添加
def add(request):
if request.method == "GET":
book_model = BookModlForm()
return render(request, "add.html", {"book_model": book_model})
else:
book_model = BookModlForm(request.POST)
if book_model.is_valid(): # 開始校驗
book_model.save() # 保存
return redirect("/show/")
else:
return render(request, "add.html", {"book_model": book_model})
<!--添加頁面-->
<form method="post" action="/add/" novalidate>
{% csrf_token %}
{% for foo in book_model %}
{{ foo.label }}
{{ foo }}
<div><span style="color: red">{{ foo.errors.0 }}</span></div>
{% endfor %}
<button type="submit" class="btn btn-default">添加</button>
</form>
# 修改
def update(request, uid):
book = models.Books.objects.filter(id=uid)[0]
if request.method == "GET":
book_model = BookModlForm(instance=book)
return render(request, "update.html", {"book_model":book_model})
else:
book_model = BookModlForm(request.POST,instance=book) # 指定更新哪條數據
if book_model.is_valid():
book_model.save()
return redirect("/show/")
else:
return render(request, "update.html", {"book_model": book_model})
# 修改頁面
<form method="post" action="">
{% csrf_token %}
{% for foo in book_model %}
<label for="{{ foo.id_for_label }}">{{ foo.label }}</label>
{{ foo }}
{% endfor %}
<button type="submit" class="btn btn-default">添加</button>
</form>