django----基于Form组件实现的增删改和基于ModelForm实现的增删改

时间:2021-01-10 02:40:28

一、ModelForm的介绍

ModelForm
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={...})

 

注意事项

            - 1. 类
class Foo(ModelForm):
class Meta:
# model = models.Role
# fields = "__all__"
# fields = ['caption',]
# exclude = ['catpion']
model = models.UserType
fields = "__all__" error_messages = {
'title':{'required':'名称不能为空','invalid':'格式错误'}
}
widgets = {
'title':wd.TextInput(attrs={'class':'c1'})
} - 2. 添加
GET:
form = Foo()
POST:
form = Foo(data=request.POST)
form.is_valid()
form.cleaned_data
form.erros
form.save()
- 3. 修改
GET:
form = Foo(instance=obj) POST:
form = Foo(instance=obj,dat=request.POST)
...
form.save()

  

表结构

from django.db import models

# Create your models here.
class UserInfo (models.Model):
username = models.CharField(max_length=32)
email = models.EmailField(max_length=32)
ut = models.ForeignKey("UserType")
class UserType (models.Model):
title = models.CharField(max_length=32)
roles = models.ManyToManyField(to="Roles")
def __str__(self):
return self.title
class Roles(models.Model):
caption = models.CharField(max_length=32)
def __str__(self):
return self.caption

  

基于Form组件的添加和编辑

from django.forms import Form, fields,widgets,ModelForm
from django.shortcuts import render,redirect,HttpResponse
from app01 import models
# Create your views here.
class RoleForm(Form):
'''利用Form'''
caption = fields.CharField(required=True,error_messages={"required":True}) def role(request):
role_obj = models.Roles.objects.all()
print(role_obj)
return render(request, "role.html",{"role_obj":role_obj}) # 基于Form实现的
def role_add(request):
'''添加角色'''
if request.method=="GET":
form = RoleForm()
return render(request,"role_add.html",{"form":form})
else:
form = RoleForm(data=request.POST)
if form.is_valid():
caption = form.cleaned_data.get("caption")
models.Roles.objects.create(caption=caption) #保存数据到数据库
# models.Roles.objects.create(**form.cleaned_data)
return redirect("/role/")
else:
return render(request,"role_add.html",{"form":form})

编辑:基于Form实现表单编辑

def role_edit(request,nid):
obj = models.Roles.objects.filter(id=nid).first() if not obj :
return HttpResponse("页面不存在")
if request.method=="GET":
form = RoleForm(initial={"caption":obj.caption}) #编辑的时候需要一个instance,让instance=一个你要编辑的那个对象
else:
form = RoleForm(data = request.POST)
if form.is_valid():
models.Roles.objects.filter(id=nid).update(**form.cleaned_data)
return redirect("/role/")
return render(request,"role_edit.html",{"form":form})

  

四、基于ModelForm的添加和编辑

添加:单表的添加

# 基于ModelForm的添加
class RoleModelForm(ModelForm):
class Meta: #这个类必须写,而且名字必须是这个
model = models.Roles #这个model也是固定的,注意不加s,
fields = "__all__" #代表所有的字段,但是你也可以指定单个的字段 def role_add(request):
if request.method == "GET":
form = RoleModelForm()
return render(request,"role_add.html",{"form":form})
else:
form = RoleModelForm(data=request.POST)
if form.is_valid():
form.save() #这里直接可以用save方法,就把数据创建了 保存到数据库了
return redirect("/role/")
else:
return render(request,"role_add.html",{"form":form})

添加:多对多的添加,一对多的提添加也是一样

# 多对多的添加
def usertype(request):
user_type_list = models.UserType.objects.all()
return render(request,"usertype.html",{'user_type_list':user_type_list}) class UserTypeModelForm(ModelForm):
title = fields.CharField(max_length=6,required=True,widget=widgets.Textarea) #这个字段是临时添加的,
# 也就是说modelForm也可以用Form的方式。
# 也可以用这样的方式新增字段, 如果有就覆盖,没有就增加;像现在这种情况就是吧下面的给覆盖了,当然没有上面的这个就用下面的了 class Meta:
model = models.UserType
fields = "__all__" error_messages = {
"title":{"required":"用户名不能为空","invalid":"邮箱格式不一致"}
}
widgets = {
"title":widgets.TextInput(attrs={"class":"c1"})
} def usertype_add(request):
if request.method=="GET":
modelform = UserTypeModelForm()
return render(request,"usertype_add.html",{"modelform":modelform})
else:
modelform = UserTypeModelForm(data=request.POST)
if modelform.is_valid():
modelform.save() #也可以用save来实现,就连关系表的字段也都添加了
return redirect("/usertype/")
else:
return render(request, "usertype_add.html", {"modelform": modelform})

#基于modelForm实现的编辑

def role_edit(request,nid):
obj = models.Roles.objects.filter(id=nid).first()
if not obj :
return HttpResponse("页面不存在")
if request.method=="GET":
form = RoleModelForm(instance=obj) #编辑的时候需要一个instance,让instance=一个你要编辑的那个对象
else:
form = RoleModelForm(data = request.POST,instance=obj)
if form.is_valid:
form.save()
return redirect("/role/")
return render(request,"role_edit.html",{"form":form})

#编辑:多对多的编辑

# 多对多的编辑
def usertype(request):
user_type_list = models.UserType.objects.all()
return render(request,"usertype.html",{'user_type_list':user_type_list}) class UserTypeModelForm(ModelForm):
title = fields.CharField(max_length=6,required=True,widget=widgets.Textarea) #这个字段是临时添加的,
class Meta:
model = models.UserType
fields = "__all__" error_messages = {
"title":{"required":"用户名不能为空","invalid":"邮箱格式不一致"}
}
widgets = {
"title":widgets.TextInput(attrs={"class":"c1"})
}
def usertype_edit(request,nid):
#查出当前类型用户对应的角色
obj = models.UserType.objects.filter(id =nid).first()
if not obj:
return HttpResponse("页面不存在")
if request.method =="GET":
form = UserTypeModelForm(instance=obj)
return render(request,"usertype_edit.html",{"form":form})
else:
form = UserTypeModelForm(instance=obj,data=request.POST)
if form.is_valid():
form.save()
return redirect("/usertype/")
return render(request,"usertype_edit.html",{"form":form})