Django form 流程
1、创建类,继承form.Form
2、页面根据类的对象自动创建html标签
3、提交,request.POST
封装到类的对象里,obj=UserInfo(request.POST)
4、用户输入是否合法
obj.is_valid()
5、全部合法,获取全部内容
obj.clean()
6、只有有不合法
obj.errors
首先关闭跨站请求
#'django.middleware.csrf.CsrfViewMiddleware',
有错误会阻止提交,并提示错误信息
成功提交,可以获取到提交的值
Form定制化
定制错误信息
mail = forms.EmailField(error_messages={'required':u'邮箱不能为空'})
定制错误规则
mobile = forms.CharField(validators=[mobile_validate,],
error_messages={'required':u'手机不能为空'})
from django.shortcuts import render
from django import forms
import re
from django.core.exceptions import ValidationError
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', #定义class
'placeholder':u'请输入手机号'}))
beizhu = forms.CharField(required=False, #备注允许为空
widget=forms.Textarea(attrs={'class':'form-control', #定义为多行输入框
'placeholder':u'请输入备注'}))
user_type_choice = (
(0,u'普通用户'),
(1,u'高级用户'),
)
user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,attrs={'class':'form-control'}))
保存用户输入内容
obj = AccountForm.LoginForm(request.POST)
Form表单验证以及错误信息
错误信息格式:
普通格式:
from django.shortcuts import render,HttpResponse
from web.forms import account as AccountForm def login(request):
obj = AccountForm.LoginForm(request.POST)
if request.method == 'POST':
if obj.is_valid():
all_data = obj.clean()
else:
#用于Form表单提交
error = obj.errors
#print error['username'][0]
#print error['password'][0]
return render(request, 'account/login.html',{'obj':obj,'error':error}) return render(request, 'account/login.html',{'obj':obj})
创建一个simple_tag,使其输 error['username'][0]
{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/login/" method="post">
<p>{{ obj.username }}
{% error_msg error.username %}
</p>
<p>{{ obj.password }}
{% error_msg error.password %}
</p>
<input type="submit" value="提交">
</form>
JSON格式
def login(request):
obj = AccountForm.LoginForm(request.POST)
if request.method == 'POST':
if obj.is_valid():
all_data = obj.clean()
else:
#用于Ajax
error = obj.errors.as_json()
#print error
return HttpResponse(error)
return render(request, 'account/login.html',{'obj':obj,'error':error})
return render(request, 'account/login.html',{'obj':obj})
<body>
<form action="/login/" method="post">
<p>{{ obj.username }}
{% error_msg error.username %}
</p>
<p>{{ obj.password }}
{% error_msg error.password %}
</p>
<input type="submit" value="Ajax提交" onclick="SubmitAjax()">
</form> <script src="{{ STATIC_URL }}js/jquery-2.1.4.min.js"></script>
<script>
function SubmitAjax(){
$.ajax({
url:'/login/',
type:'POST',
data:{'username':'','password':''},
success:function(arg){
console.log(arg)
}
})
}
</script>
</body>
Form生成select标签
静态select
动态select
当增加数据库数据时
不会更新,除非关闭程序,重新载入才会更新
解决方法:利用面向对象类的静态字段
from django import forms
import json class ImportForm(forms.Form):
#静态select
HOST_TYPE_LIST = (
(0,'物理机'),
(1,'虚拟机'),
)
host_type = forms.IntegerField(
widget=forms.Select(choices=HOST_TYPE_LIST)
)
hostname = forms.CharField() #动态select
# admin_dic = ((1,'yangmv'),(1,"bob"),)
# w_obj = open('db_admin','w')
# w_obj.write(json.dumps(admin_dic))
# w_obj.close()
f_obj = open('db_admin','r')
data = f_obj.read()
data_tuple = json.loads(data)
admin = forms.IntegerField(
widget=forms.Select(choices=data_tuple)
) def __init__(self,*args,**kwargs):
super(ImportForm,self).__init__(*args,**kwargs)
tmp = open('db_admin')
data = tmp.read()
data_tuple = json.loads(data)
self.fields['admin'].widget.choices = data_tuple
再次增加数据库数据,直接刷新页面即可读取到新数据
优化后代码
from django import forms
import json class ImportForm(forms.Form):
admin = forms.IntegerField(widget=forms.Select())
def __init__(self,*args,**kwargs):
super(ImportForm,self).__init__(*args,**kwargs)
tmp = open('db_admin')
data = tmp.read()
data_tuple = json.loads(data)
self.fields['admin'].widget.choices = data_tuple
使用models获取select数据
(models操作,后面一偏文章会详细介绍)
class Select(models.Model):
username = models.CharField(max_length=16)
password = models.CharField(max_length=32)
<body>
<form action="/home/">
<p>{{ obj.admin }}</p>
</form>
</body>
def home(request):
obj = HomeForm.ImportForm()
return render(request, 'home/home.html',{'obj':obj})
models.Select.objects.all().values_list('id','username')