文章目录
2019-1-3 18:11:54
Django之Form表单
- 简单应用(需修改)
########################views.py#####################
from django import forms
from app01 import models
from django.forms import widgets
from django.forms import fields
class FM(forms.Form):
# 字段本身只做验证
user = fields.CharField(
error_messages={'required': '用户名不能为空.'},
widget=widgets.Textarea(attrs={'class': 'c1'}),
label="用户名",
)
pwd = fields.CharField(
max_length=12,
min_length=6,
error_messages={'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12'},
widget=widgets.PasswordInput(attrs={'class': 'c2'})
)
email = fields.EmailField(error_messages={'required': '邮箱不能为空.','invalid':"邮箱格式错误"})
f = fields.FileField()
# p = fields.FilePathField(path='app01')
city1 = fields.ChoiceField(
choices=[(0,'上海'),(1,'广州'),(2,'东莞')]
)
city2 = fields.MultipleChoiceField(
choices=[(0,'上海'),(1,'广州'),(2,'东莞')]
)
def fm(request):
if request.method == "GET":
# 从数据库中吧数据获取到
dic = {
"user": 'r1',
'pwd': '123123',
'email': 'sdfsd',
'city1': 1,
'city2': [1,2]
}
obj = FM(initial=dic)
return render(request,'fm.html',{'obj': obj})
elif request.method == "POST":
# 获取用户所有数据
# 每条数据请求的验证
# 成功:获取所有的正确的信息
# 失败:显示错误信息
obj = FM(request.POST)
r1 = obj.is_valid()
if r1:
# obj.cleaned_data
models.UserInf.objects.create(**obj.cleaned_data)
else:
# ErrorDict
# print(obj.errors.as_json())
# print(obj.errors['user'][0])
return render(request,'fm.html', {'obj': obj})
return render(request,'fm.html')
#########################fm.html########################
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/fm/" method="POST">
{% csrf_token %}
<p>{{ obj.user.label }} {{ obj.user }} {{ obj.errors.user.0 }}</p>
<p>{{ obj.pwd }} {{ obj.errors.pwd.0 }}</p>
<p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
<p>{{ obj.f }}{{ obj.errors.f.0 }}</p>
{{ obj.city1 }}
{{ obj.city2 }}
<input type="submit" value="提交" />
</form>
</body>
</html>