Python自动化之modelform和原生ajax
modelform验证
`views.py`
from django.shortcuts import render,HttpResponse
from app01 import models
from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
class UserInfoModelForm(forms.ModelForm):
is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())
class Meta:
model = models.UserInfo
fields = '__all__'
# fields = ['username','email']
# exclude = ['username']
modelform修改
views.py
def user_edit(request, nid):
# 获取当前id对象的用户信息
# 显示用户已经存在数据
if request.method == "GET":
user_obj = models.UserInfo.objects.filter(id=nid).first()
mf = UserInfoModelForm(instance=user_obj) //初始化数据
return render(request,'user_edit.html',{'mf': mf, 'nid': nid})
elif request.method == 'POST':
user_obj = models.UserInfo.objects.filter(id=nid).first()
mf = UserInfoModelForm(request.POST,instance=user_obj) //更新数据
if mf.is_valid():
mf.save()
else:
print(mf.errors.as_json())
return render(request,'user_edit.html',{'mf': mf, 'nid': nid})
views.py
def index(request):
if request.method == "GET":
obj = UserInfoModelForm()
return render(request,'index.html',{'obj': obj})
elif request.method == "POST":
obj = UserInfoModelForm(request.POST)
if obj.is_valid():
# obj.save()
instance = obj.save(False) //多对多保存
instance.save() //多对多保存
obj.save_m2m() //多对多保存
form表单初始化需要在
form
实例添加initial
,例如:obj=UserFrom(initial={'name':'wushi'}),initial值是个字典
modelform总结
1. 生成HTML标签:class Meta: ...
2. mf = xxxModelForm(instance=ModelObj)
3. 额外的标签, is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())
4. 各种验证 is_valid() -> 各种钩子...
5. mf.save()
# 或
instance = mf.save(False)
instance.save()
mf.save_m2m()
原生ajax向后台提交数据
function Ajax1(){
var xhr = getXHR();
//var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax_json/',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.setRequestHeader('k1','v1');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); //这是请求头是必须写的,这样django才能取到数据
xhr.send("name=root;pwd=123");
}
ajax兼容IE
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
伪ajax,通过ifram进行数据的发送
function sumitForm(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
})
}
ifram接受到的数据,不是存在ifram标签里面而是一个document,也就是一个网页文档
所以可以绑定一个load事件,在其加载完之后取值.
感谢关注