表单
表单可以验证输入,也可以生成html
<form action="/user_list/" method="post">
<p>用户类型:{{ obj.user_type }}
<span>{% error_message errors.user_type %}</span>
</p>
<p>主机:{{ obj.host }}
<span>{% error_message errors.host %}</span>
</p>
<p>端口:{{ obj.port }} <span>{{ errors.port }}</span></p>
<p>邮箱:{{ obj.email }} <span>{{ errors.email }}</span></p>
<p>手机:{{ obj.mobile }} <span>{{ errors.mobile }}</span></p>
<p>备注:{{ obj.memo }} <span>{{ errors.memo }}</span></p>
<input type="submit" value="submit" />
</form>
#z自定义匹配类型
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('手机号码格式错误')
#创建一个继承Form的类
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': u'邮箱不能为空'}) #自定义表单错误提示
host = forms.CharField(error_messages={'required': u'主机不能为空'})
port = forms.CharField(error_messages={'required': u'端口不能为空'})
mobile = forms.CharField(validators=[mobile_validate, ], #调用自己定义的匹配函数
error_messages={'required': u'手机不能为空'},
widget=forms.TextInput(attrs={'class': "form-control", #添加标签属性
'placeholder': u'手机号码'}))
memo = forms.CharField(required=False,
widget=forms.Textarea(attrs={'class': "form-control",
'placeholder': u'备注'})
)
#前端提交数据处理函数
def user_list(request):
obj = UserInfo()
if request.method == "POST":
user_input_obj = UserInfo(request.POST)
if user_input_obj.is_valid():
data = user_input_obj.clean()
print data
else:
error_msg = user_input_obj.errors.as_data()
return render(request, 'user_list.html', {'obj': user_input_obj, 'errors': error_msg})
return render(request, 'user_list.html', {'obj': obj})