1. 程式人生 > >django-Form組件

django-Form組件

coo 是否 選項 document urn not int ora div

1 Form表單定義

from django.forms import Form
from django.forms import fields
from django.forms import widgets
import re
from django.core.exceptions import ValidationError

class UserLogin(Form):
username = fields.CharField(
required=True,
error_messages={‘required‘:‘用戶名不能為空‘},
widget=widgets.TextInput(attrs={‘class‘:‘txtcss_user‘})
)
password = fields.CharField(
required=True,
error_messages={‘required‘: ‘密碼不能為空‘},
widget=widgets.PasswordInput(attrs={‘class‘: ‘txtcss_pwd‘})
)

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(‘手機號碼格式錯誤‘)

class SignUpForm(Form):
username=fields.CharField(
min_length=5,max_length=20,
error_messages={‘required‘: ‘用戶名不能為空‘,
‘min_length‘: u‘用戶名最少為5個字符‘,
‘max_length‘: u‘標題最多為20個字符‘,
},
widget=widgets.TextInput(attrs={"class": "txtcss_usual txt_username",‘placeholder‘: u‘用戶名5-20個字符‘})
)
phone = fields.CharField(
validators=[mobile_validate, ],
error_messages={‘required‘: ‘手機號不能為空‘},
widget=widgets.TextInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘手機號碼‘})
)
password=fields.CharField(
min_length=5,
error_messages={‘required‘: ‘密碼不能為空‘,‘min_length‘: u‘密碼最少為5個字符‘,},
widget=widgets.PasswordInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘密碼‘})
)
pwd_confirm=fields.CharField(
error_messages={‘required‘: ‘確認密碼不能為空‘},
widget=widgets.PasswordInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘確認密碼‘})
)
email=fields.EmailField(
required=False,
error_messages={‘required‘: ‘郵箱不能為空‘,‘invalid‘: u‘郵箱格式錯誤‘},
widget=widgets.TextInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘郵箱‘})
)
def clean(self):
pwd = self.cleaned_data.get("password")
pwd_confirm = self.cleaned_data.get("pwd_confirm")
if pwd == pwd_confirm:
return self.cleaned_data
else:
self.add_error("pwd_confirm",ValidationError("密碼輸入不一致"))
return self.cleaned_data


2 Form表單使用
2.1 views視圖
if request.method == ‘POST‘:
response = {‘status‘: True, ‘data‘: None, ‘msg‘: None, ‘query‘: None}
valid_code = request.POST.get("valid_code")
session_valid = request.session.get("valid_code")
if valid_code.upper() == session_valid.upper():
regForm = forms.SignUpForm(request.POST)
if regForm.is_valid():
username=regForm.cleaned_data.get("username")
password=regForm.cleaned_data.get("password")
email=regForm.cleaned_data.get("email")
phone = regForm.cleaned_data.get("phone")
user=models.UserInfo.objects.create_user(
username=username,
password=password,
email=email,
telephone=phone,
)
else:
print(regForm.errors)
response["status"] = False
response["msg"]=regForm.errors # errors只存錯誤字段
else:
response[‘status‘] = False
response[‘query‘] = ‘驗證碼錯誤。‘
return HttpResponse(json.dumps(response))
else:
regForm = forms.SignUpForm()
return render(request,‘signup.html‘,{"form":regForm})

2.2 模板中的signup.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>註冊</title>
<link rel="stylesheet" href="{% static ‘dist/css/bootstrap.min.css‘ %}">
<link rel="stylesheet" href="{% static ‘css/login.css‘ %}">
<link rel="stylesheet" href="{% static ‘css/_layout.min.css‘ %}">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1"
style="border-radius: 8px;border: 1px solid #e1e1e8;margin-top: 100px;padding-bottom:30px;padding-top: 10px;">
<div class="row">
<div class="col-md-10 col-md-offset-1" style="border-bottom: 1px solid #e1e1e8;margin-bottom: 30px;">
<h3>註冊新用戶</h3>
</div>
</div>
<div class="row">
<div class="col-md-12" style="line-height: 50px;font-size: 18px;">
<form id="form1">
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="username">用戶名:</label>
</div>
<div class="col-md-8">{{ form.username }}</div>
<input id="is_exist_user" type="hidden" value="False" />
</div>
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="email">郵箱:</label>
</div>
<div class="col-md-8">{{ form.email }}</div>
</div>
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="phone">手機號:</label>
</div>
<div class="col-md-8">{{ form.phone }}</div>
</div>
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="password">密碼:</label>
</div>
<div class="col-md-8">{{ form.password }}</div>
</div>
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="pwd_confirm">確認密碼:</label>
</div>
<div class="col-md-8">{{ form.pwd_confirm }}</div>
</div>
<div class="row">
<div class="col-md-4" style="text-align: right;">
<label for="valid_code">驗證碼:</label>
</div>
<div class="col-md-8">
<input type="text" name="valid_code" class="txtcss_code" placeholder="驗證碼"/>
<a href="#"><img class="valid_img" src="/get_valid_img/" mypath="/get_valid_img/"
alt="ok" width="200" height="40"></a>
</div>
</div>
<div class="row" style="margin-top: 10px;">
<div class="col-md-7" style="text-align: right;">
<a href="#" class="btn btn-primary btn-lg" style="width:150px" onclick="submitForm();"
id="submit">註冊</a>
</div>
<div class="col-md-5">
<span id="login_fail"></span>
</div>
{% csrf_token %}
</div>
</form>

</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" style="text-align: center;font-size: 16px; margin-top: 30px;">
&copy; 2017-2020 www.ship.com.cn All Rights Reserved.我的博客 版權所有
</div>
</div>
</div>

<script src="{% static ‘js/jquery-2.2.0.min.js‘ %}"></script>
<script src="{% static ‘js/jquery.cookie.js‘ %}"></script>
<script src="{% static ‘js/jquery.myConfirm.js‘ %}"></script>
<script src="{% static ‘js/nav-iconfont.js‘ %}"></script>
<script src="{% static ‘js/_layout.min.js‘ %}"></script>
<script type="text/javascript">
$(".valid_img").click(function () {
console.log($(this).attr("mypath")+Math.random());
$(this)[0].src=$(this).attr("mypath")+Math.random();
});

$(".txt_username").blur(function () {
var username = $(this).val();
// 判斷輸入框是否為空
if (username == ""){
return false;
}
$.ajax({
url: ‘/valid_username/‘,
type: ‘POST‘,
data: {"username":username,"csrfmiddlewaretoken":$("input[name=‘csrfmiddlewaretoken‘]").val()},
dataType: ‘JSON‘,
success: function (arg) {
if (arg.status) {
$("#is_exist_user").val("True");
var tag = document.createElement(‘span‘);
tag.innerHTML = "用戶名存在";
tag.className = "error";
$(‘#form1 input[name="username"]‘).after(tag);
}
else {
$("#is_exist_user").val("False");
}
}
})
});

function submitForm() {
if($("#is_exist_user").val()=="True"){
return false;
}
$(‘#form1 .error‘).remove();
$.ajax({
url: ‘/signup/‘,
type: ‘POST‘,
data: $(‘#form1‘).serialize(),
dataType: ‘JSON‘,
success: function (arg) {
if (arg.status) {
location.href = "/login/";
} else {
if (arg.query) {
var tag = document.createElement(‘span‘);
tag.innerHTML = arg.query;
tag.className = "error";
$(‘#login_fail‘).after(tag);
}
$.each(arg.msg, function (k, v) {
var tag = document.createElement(‘span‘);
tag.innerHTML = v[0];
tag.className = "error";
$(‘#form1 input[name="‘ + k + ‘"]‘).after(tag);
})
}
}
})
}
</script>

</body>
</html>


3 Form表單鉤子
class SignUpForm(Form):
username=fields.CharField(
min_length=5,max_length=20,
error_messages={‘required‘: ‘用戶名不能為空‘,
‘min_length‘: u‘用戶名最少為5個字符‘,
‘max_length‘: u‘標題最多為20個字符‘,
},
widget=widgets.TextInput(attrs={"class": "txtcss_usual txt_username",‘placeholder‘: u‘用戶名5-20個字符‘})
)
password=fields.CharField(
min_length=5,
error_messages={‘required‘: ‘密碼不能為空‘,‘min_length‘: u‘密碼最少為5個字符‘,},
widget=widgets.PasswordInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘密碼‘})
)
pwd_confirm=fields.CharField(
error_messages={‘required‘: ‘確認密碼不能為空‘},
widget=widgets.PasswordInput(attrs={"class": "txtcss_usual",‘placeholder‘: u‘確認密碼‘})
)
def clean(self):
pwd = self.cleaned_data.get("password")
pwd_confirm = self.cleaned_data.get("pwd_confirm")
if pwd == pwd_confirm:
return self.cleaned_data
else:
self.add_error("pwd_confirm",ValidationError("密碼輸入不一致"))
return self.cleaned_data


4 內置字段
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類型

5 內置插件
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

6 常用插件
# 單radio,值為字符串
user = fields.CharField(
initial=2,
widget=widgets.RadioSelect(choices=((1,‘上海‘),(2,‘北京‘),))
)

# 單radio,值為字符串
user = fields.ChoiceField(
choices=((1, ‘上海‘), (2, ‘北京‘),),
initial=2,
widget=widgets.RadioSelect
)

# 單select,值為字符串
user = fields.CharField(
initial=2,
widget=widgets.Select(choices=((1,‘上海‘),(2,‘北京‘),))
)

# 單select,值為字符串
user = fields.ChoiceField(
choices=((1, ‘上海‘), (2, ‘北京‘),),
initial=2,
widget=widgets.Select
)

# 多選select,值為列表
user = fields.MultipleChoiceField(
choices=((1,‘上海‘),(2,‘北京‘),),
initial=[1,],
widget=widgets.SelectMultiple
)

# 單checkbox
user = fields.CharField(
widget=widgets.CheckboxInput()
)

# 多選checkbox,值為列表
user = fields.MultipleChoiceField(
initial=[2, ],
choices=((1, ‘上海‘), (2, ‘北京‘),),
widget=widgets.CheckboxSelectMultiple
)

django-Form組件