django中的Form一般有两种功能:
- 输入html
- 验证用户输入
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>原生的html</h1>
<form action="/web/register/" method="POST">
用户名:<input name="username" placeholder="username"/>
<br/>
密码:<input name="password" placeholder="password"/>
<br/>
<input type="submit" value="提交"/>
</form>
<h1>form的html</h1>
<form action="" method="POST">
用户名:{{ data.username }}
<br/>
密码:{{ data.email }}
<br/>
IP:{{ data.ip }}
<br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
一个form页面:
from django import forms
class alogin(forms.Form):
username = forms.CharField()
email = forms.EmailField(required=True)
ip = forms.GenericIPAddressField()
views:
def index(request):
obj = forms.alogin()
if request.method == 'POST':
checkform = forms.alogin(request.POST)#此时的request.POST就是一个字典
checkresult = checkform.is_valid()#判断是否是正确类型
print checkresult
return render_to_response('app03/index.html', {'data': obj})
返回错误信息的views:
if request.method == 'POST':
checkform = forms.alogin(request.POST)
checkresult = checkform.is_valid()
if checkresult:
print '通过验证'
else:
errorinfo = checkform.errors
#print errorinfo
return render_to_response('app03/index.html', {'data': obj,'error':errorinfo})
具体参考:http://www.cnblogs.com/wupeiqi/articles/5246483.html