django form的作用
1、生成html标签
2、验证输入内容
form生成表单
zhuji/forms.py
- 实例化表单
- 定制form错误信息
- 定制表单类型
from django import forms
class UserInfo(forms.Form):
user_type_choice = (
(0, u\'普通用户\'),
(1, u\'高级用户\'),
)
user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,
attrs={\'class\': "form-control"}))
email = forms.EmailField(error_messages={\'required\': "邮箱不能为空"})
host = forms.CharField(error_messages={\'required\': "主机不能为空"})
port = forms.CharField(error_messages={\'required\': "端口不能为空"},
widget=forms.TextInput(attrs={\'class\': "form-control", \'placeholder\': "端口"})
)
mobile = forms.CharField(error_messages={\'required\': "手机不能为空"},
widget=forms.Textarea(attrs={\'class\': "form-control", \'placeholder\': "手机号码"})
)
zhuji/views.py
from zhuji.forms import UserInfo
def user_list(request):
obj = UserInfo()
if request.method == "POST":
user_input_obj = UserInfo(request.POST) #实例化form表单
if user_input_obj.is_valid():#form验证通过
data = user_input_obj.clean()#前端表单获取成一个dict
hostname = data[\'host\']#取出host字段
print(data)
print(hostname)
else:
error_msg = user_input_obj.errors
return render(request, "user_list.html", {\'obj\': user_input_obj, \'errors\': error_msg})#错误信息返回
return render(request, \'user_list.html\', {\'obj\': obj})
templates/user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user_list</title>
</head>
<body>
<div>
<form action="/user_list/" method="post">
<p>用户类型: {{ obj.user_type }} <span>{{ errors.user_type }}</span></p>
<p>主机: {{ obj.host }} <span>{{ errors.host }}</span></p>
<p>邮箱: {{ obj.email }} <span>{{ errors.email }}</span></p>
<p>端口: {{ obj.port }} <span>{{ errors.port }}</span></p>
<p>手机: {{ obj.mobile }} <span>{{ errors.mobile }}</span></p>
<p><input type="submit"></p>
{% csrf_token %}
</form>
</div>
</body>
</html>