python第一百一十七天-----ModelForm组件

时间:2023-12-27 20:24:25
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()
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={...}) 示例: 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" value="提交" />
</form>
</body>
</html>

models.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(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#插件 as 设置别名 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 = {#自定义插件 使用 form的插件
'username': Fwidgets.Textarea(attrs={'class': 'c1'})
}
error_messages = {
'__all__':{
#整体的错误信息
},
'email': {#指定的错误信息
'required': '邮箱不能为空',
'invalid': '邮箱格式错误..',
}
}
field_classes = {#字段的类
# 'email': Ffields.URLField
} # localized_fields=('ctime',) 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):
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()#保存对应表的关系的表 # print(obj.is_valid())
# print(obj.cleaned_data)
# print(obj.errors.as_json())
return render(request,'index.html',{'obj': obj}) #用户列表
def user_list(request):# 所有 跨表条件
li = models.UserInfo.objects.all().select_related('user_type')
return render(request,'user_list.html',{'li': li})
#用户信息编辑
def user_edit(request, nid):
# 获取当前id对象的用户信息
# 显示用户已经存在数据
if request.method == "GET":
user_obj = models.UserInfo.objects.filter(id=nid).first()
#调用ModelForm 默认值
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})

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 method="POST" action="/edit-{{ nid }}/">
{% csrf_token %}
{{ mf.as_p }}
<!--显示当前对象的所有信息-->
<input type="submit" value="提交" />
</form> </body>
</html>