Form
一、使用Form
Django中的Form使用时一般有两种功能:
1、生成html标签
2、验证输入内容
要想使用django提供的form,要在views里导入form模块
from django import forms
然后再定义一个类,这个类就是要在前端html页面中生成form表单中的input标签的。
class UserInfo(forms.Form):
email = forms.EmailField()
host = forms.CharField()
port = forms.CharField()
mobile = forms.CharField()
自定义From的流程:
二、多说无益,直接看代码:
# coding:utf-8 from django import forms class UserInfo(forms.Form): #定义的django表单
email = forms.EmailField()
host = forms.CharField()
port = forms.CharField()
mobile = forms.CharField() def user_list(request): obj =UserInfo() #创建form的对象
if request.method == "POST":
user_input_obj = UserInfo(request.POST) #request.POST为提交过来的所有数据 if user_input_obj.is_valid(): #is_valid判断输入的内容是否合法 Ture 或False
data = user_input_obj.clean() #.clen()获取提交的数据 host_name = data['host']
print data
print host_name
else: #如果输入不合法,返回错误信息
error_msg = user_input_obj.errors #errors为错误信息
return render(request,'user_list.html',{'obj':user_input_obj,'errors':error_msg})
#将错误信息直接返回到前端页面去展示
return render(request,'user_list.html',{'obj':obj})
前端html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body> <form action="/user_list/" method="post">
<p>主机:{{ obj.host }} <span>{{ 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>
<input type="submit" value="submit"> </form> </body>
</html>
三、自定义Form
1、自定义错误提示信息
error_messages={'required': u'手机不能为空'},
class UserInfo(forms.Form):
email = forms.EmailField(error_messages={'required': u'邮箱不能为空'},)
host = forms.CharField(error_messages={'required': u'主机不能为空'},)
port = forms.CharField(error_messages={'required': u'端口不能为空'},)
mobile = forms.CharField(error_messages={'required': u'手机不能为空'},)
2、自定义Form的样式属性
widget=forms.TextInput(attrs={'class': "form-control",
'placeholder': u'手机号码'}),
class UserInfo(forms.Form):
email = forms.EmailField(error_messages={'required': u'邮箱不能为空'},)
host = forms.CharField(error_messages={'required': u'主机不能为空'},)
port = forms.CharField(error_messages={'required': u'端口不能为空'},)
mobile = forms.CharField(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"备注"}))
3、自定义验证Form表单中的内容是否合法:
validators=[mobile_validate, ],
from django.core.exceptions import ValidationError
import re 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 UserInfo(forms.Form):
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"备注"}))
4、自定义Form中的select
class UserInfo(forms.Form): user_type_choice = (
(, u'普通用户'),
(, 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"备注"}))
5、自定义错误信息的样式
1、Form错误信息:
如果不做任何处理,错误信息的显示会有一个默认<ul>的样式,我们可以把它去掉,在错误信息的后面添加 as_data(),显示原始的数据。
- user_input_obj.errors.as_data()
仅这样做还不够,还需要在前端页面标签中取出错误信息。但模板语言不支持索引的取值方式,所以这里还需要与python的结合
在app的目录下创建一个templatetags目录,然后创建一个py文件,取名为form_tag.py
#!/usr/bin/env python
# -*- coding:utf-8 -*- from django import template register = template.Library() @register.simple_tag
def error_message(arg):
if arg:
return arg[0][0]
else:
return ''
然后再前端页面导入form_tag,并使用
{% load form_tag %} 导入py文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body> <form action="/app01/user_list/" method="post">
<p>用户类型:{{ obj.user_type }} <span>{{ errors.user_type }}</span></p>
<p>主机:{{ obj.host }} <span style="color: red;">{% 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> </body>
</html>
2、Ajax错误信息:
- user_input_obj.errors.as_json()
html文件:定义ajax
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body> <form action="/login/" method="post">
<p>{{ obj.username }}</p>
<p>{{ obj.password }}</p>
<input type="submit" value="submit">
<input type="button" onclick="Ajax();" value="Ajax">
</form> {#<script type="text/javascript" src="{{ STATIC_URL }}/js/jquery-2.1.4.min.js">#}
<script type="text/javascript" src="{% static "js/jquery-2.1.4.min.js" %}"></script>
<script>
function Ajax(){
$.ajax({
url:'/login/',
type:'POST',
data:{'username':'','password':''},
success:function(arg){
console.log(arg);
}
})
}
</script>
</body>
</html>
后台处理:
返回数据时,要用HttpResponse
def login(request): obj = Account_Forms.UserInfo(request.POST)
if request.method == 'POST':
if obj.is_valid():
data = obj.clean()
print data else:
error_msg = obj.errors.as_json()
return HttpResponse(error_msg) #用HttpResponse的方式返回数据
return render(request, 'account/login.html', {'obj': obj})
return render(request, 'account/login.html', {'obj': obj})