s14_08_ModelForm
ModelForm组件
参考博客:
http://www.cnblogs.com/wupeiqi/articles/6229414.html
ModelForm(武sir博客)
a. class Meta:
model, # 对应Model的
fields=None, # 字段
exclude=None, # 排除字段
labels=None, # 提示信息
help_texts=None, # 帮助提示信息
widgets=None, # 自定义插件
error_messages=None, # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
field_classes=None # 自定义字段类 (也可以自定义字段)
localized_fields=('birth_date',) # 本地化,如:根据不同时区显示数据
如:
数据库中
2016-12-27 04:10:57
setting中的配置
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
则显示:
2016-12-27 12:10:57
b. 验证执行过程
is_valid -> full_clean -> 钩子 -> 整体错误
c. 字典字段验证
def clean_字段名(self):
# 可以抛出异常
# from django.core.exceptions import ValidationError
return "新值"
d. 用于验证
model_form_obj = XXOOModelForm()
model_form_obj.is_valid()
model_form_obj.errors.as_json()
model_form_obj.clean()
model_form_obj.cleaned_data
e. 用于创建
model_form_obj = XXOOModelForm(request.POST)
#### 页面显示,并提交 #####
# 默认保存多对多
obj = form.save(commit=True)
# 不做任何操作,内部定义 save_m2m(用于保存多对多)
obj = form.save(commit=False)
obj.save() # 保存单表信息
obj.save_m2m() # 保存关联多对多信息
f. 用于更新和初始化
obj = model.tb.objects.get(id=1)
model_form_obj = XXOOModelForm(request.POST,instance=obj)
...
PS: 单纯初始化
model_form_obj = XXOOModelForm(initial={...})
- 要点:
Model + Form => 验证 + 数据库操作
- class LoginModelForm(xxxxx):
利用model.A中的字段
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()
- 代码:
# views.py
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^user_list/', views.user_list),
url(r'^edit-(\d+)/', views.user_edit),
# model.py
from django.db import models
# Create your models here.
class UserType(models.Model):
caption = models.CharField(max_length=32)
class UserGroup(models.Model):
name = models.CharField(max_length=32)
class UserInfo(models.Model):
# username = models.CharField(verbose_name='用户',max_length=32)
username = models.CharField(verbose_name='用户',max_length=32)
email =models.EmailField()
user_type =models.ForeignKey(to='UserType',to_field='id')
u2g= models.ManyToManyField(UserGroup)
# 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
# Create your views here.
class UserInfoModelForm(forms.ModelForm):
is_rmb = Ffields.CharField(
widget=Fwidgets.CheckboxInput()
)
class Meta:
model = models.UserInfo
fields = '__all__'
# fields = ['username','email'] # 指定部分字段
# exclude = ['username'] # 排除部分字段
labels={
'username':'用户名',
'email':'邮箱',
}
help_texts={
'username':'...'
}
widgets = {
'username':Fwidgets.Textarea(attrs={'class':'c1'})
}
error_message = {
'__all__':{
},
'email':{
'required':'邮箱不能为空',
'invalid':'邮箱格式错误'
}
}
field_classes = {
# 'email':Ffields.URLField
}
# localized_fields=('ctime',)
# 钩子验证同form
def clean_username(self):
old = self.cleaned_data['username']
return old
class UserInfoForm(forms.Form):
username = Ffields.CharField(max_length=32)
email =Ffields.EmailField()
user_type =Ffields.ChoiceField(
choices=models.UserType.objects.values_list('id','caption')
)
def __init__(self,*args,**kwargs):
super(UserInfoForm,self).__init__(*args,**kwargs)
self.fields['user_type'].choices=models.UserType.objects.values_list('id','caption')
def index(request):
# form 代码
# if request.method=='GET':
# obj =UserInfoForm()
# return render(request,'index.html',{'obj':obj})
# elif request.method=="POST":
# obj =UserInfoForm(request.POST)
# obj.is_valid()
# obj.cleaned_data
# obj.errors
# # models.UserInfo.objects.create(**obj.cleaned_data)
# models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data)
# return render(request,'index.html',{'obj':obj})
# modelform代码
if request.method=='GET':
obj = UserInfoModelForm ()
return render(request,'index.html',{'obj':obj})
elif request.method=="POST":
obj =UserInfoModelForm(request.POST)
# print(obj.is_valid())
# print(obj.cleaned_data)
# print(obj.errors.as_json)
if obj.is_valid():
# obj.save()
# 拆分上步骤
instance = obj.save(False)
instance.save() # 只保存当前类
obj.save_m2m()
return render(request,'index.html',{'obj':obj})
def user_list(request):
li = models.UserInfo.objects.all().select_related('user_type')
# li = models.UserInfo.objects.all().select_related('user_type','u2g')
# 不能选择u2g
return render(request,'user_list.html',{'li':li})
def user_edit(request,nid):
if request.method=='GET':
# 获取当前id用户信息,显示已存在数据
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})
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/index/" method="POST">
{% csrf_token %}
{{ obj.as_p}}
<input type="submit">
</form>
</body>
</html>
# user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
{% for row in li %}
<li>{{ row.username }} - {{ row.user_type.caption }} - <a href="/edit-{{ row.id }}/">编辑</a></li>
{% endfor %}
</ul>
</body>
</html>
# user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/edit-{{ nid }}/"method="POST">
{% csrf_token %}
{{ mf.as_p }}
<input type="submit">
</form>
</body>
</html>