循序渐进PYTHON3(十三) --3-- DJANGO之FORM表单(为自动生成的HTML标签添加样式)
views.py
from django.shortcuts import render,HttpResponse
from django import forms
import json
import re
from django.core.exceptions importValidationError
# Create your views here.
def mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
ifnot mobile_re.match(value):
raiseValidationError('手机号码格式错误')
classInputForm(forms.Form):
# 下面使用的变量名必须和html中input标签的name值相同
# forms 的字段类型包括:IntegerField,CharField,URLField,EmailField,DateField等,但是没有手机号
# required=True表示对输入做验证
# error_messages 自定制提示信息
username = forms.CharField(required=True, error_messages={'required':'用户名不能为空'})
password = forms.CharField(required=True,
min_length=8,
max_length=20,
error_messages={'required':'密码不能为空','min_length':'至少6位',
'max_length':'至多10位'}
)
num = forms.IntegerField(error_messages={'required':'不能为空','invalid':'必须是数字'})
# 自定制验证方法关键就是参数validators,和自己的函数关联起来
phone = forms.CharField(validators=[mobile_validate,],)
# django给标签加sytle,关键参数widget ,forms.TextInput 表示生成type="text"的input标签,改成Textarea则生成<textarea>标签
test = forms.CharField(widget=forms.TextInput(attrs={'class':'in_tmp'}))
choice =(
(1,'北京'),
(2,'上海')
)
t_choice = forms.IntegerField(widget=forms.Select(choices=choice))
def login(request):
if request.POST:
objPost =InputForm(request.POST)
ret = objPost.is_valid()
if ret:
print(objPost.clean())
# else:
# # from django.forms.utils import ErrorDict
# print(type(objPost.errors),objPost.errors.as_json())
return render(request,'login.html',{'data': objPost})
else:
objGet =InputForm()
return render(request,'login.html',{'data': objGet})
login.html
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
<style>
.error-msg{
color:red;
}
.in_tmp{
border:1px solid #6a34ff ;
}
</style>
</head>
<body>
<formaction="/login/"method="POST">
<div>
<div>
{{ data.username }}
{% if data.errors.username %}
<spanclass="error-msg">{{ data.errors.username.0 }}</span>
{% endif %}
</div>
<div>
{{ data.password }}
{% if data.errors.password %}
<spanclass="error-msg">{{ data.errors.password.0 }}</span>
{% endif %}
</div>
<div>
{{ data.num }}
{% if data.errors.num %}
<spanclass="error-msg">{{ data.errors.num.0 }}</span>
{% endif %}
</div>
<div>
{{ data.phone }}
{% if data.errors.phone %}
<spanclass="error-msg">{{ data.errors.phone.0 }}</span>
{% endif %}
</div>
<div>
{{ data.test }}
{% if data.errors.test %}
<spanclass="error-msg">{{ data.errors.test.0 }}</span>
{% endif %}
</div>
<div>
{{ data.t_choice }}
{% if data.errors.t_choice %}
<spanclass="error-msg">{{ data.errors.t_choice.0 }}</span>
{% endif %}
</div>
<inputtype="submit"value="提交"/>
</div>
</form>
</body>
</html>
效果图:
select 标签显示数据库数据: