1. modelform可以帮助我们生成html标签
class UserModelForm(forms.ModelForm):
# 重新添加效验
name = forms.CharField(min_length=3, label="用户名")
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password",] # 获取表头
form = UserModelForm()
{{ form.name }} 普通的input框
{{ form.password }} 普通的input框
2. 可以定义插件
# 第一种
class UserModelForm(forms.ModelForm):
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password",] # 获取表头
widgets={
"name": forms.TextInput(attrs={"class":"form-control"}),
"password": forms.PasswordInput(attrs={"class":"form-control"})
}
# 第二种
class UserModelForm(forms.ModelForm):
name = forms.CharField(min_length=3,
label="用户名",
widgets={"name": forms.TextInput(attrs={"class":"form-control"}
)
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password",] # 获取表头
{{ form.name }} BootStrap的input框
{{ form.password }} BootStrap的input框
3. 重新定义init方法,批量设置
class UserModelForm(forms.ModelForm):
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password", "age", ] # 获取表头
def __init__(self, *args, **kwargs): # 重写父类方法
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置attrs
for name, field in self.fields.items():
field.widget.attrs = {
"class": "form-control",
"placeholder": field.label} # 获取数据库备注信息:field.label
重新定义init方法,批量设置:优化
class UserModelForm(forms.ModelForm):
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password", "age", ] # 获取表头
def __init__(self, *args, **kwargs): # 重写父类方法
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置attrs
for name, field in self.fields.items():
# 如果字段中有属性,保留原来的属性,没有属性,才增加
if field.widget.attrs:
field.widget.attrs["class"]="form-control"
field.widget.attrs["placeholder"]="field.label"
else:
field.widget.attrs = {
"class": "form-control",
"placeholder": field.label} # 获取数据库备注信息:field.label
4. 重复写,太麻烦,自定义公共父类
class BootStrapModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs): # 重写父类方法
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置attrs
for name, field in self.fields.items():
# 如果字段中有属性,保留原来的属性,没有属性,才增加
if field.widget.attrs:
field.widget.attrs["class"]="form-control"
field.widget.attrs["placeholder"]="field.label"
else:
field.widget.attrs = {
"class": "form-control",
"placeholder": field.label} # 获取数据库备注信息:field.label
5. 子类继承
class UserModelForm(BootStrapModelForm):
class Meta:
model = models.User # 获取数据库User类的验证规则
fields = ["name", "password", "age", ] # 获取表头
6. 例子
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
from django import forms
#############ModelForm实例###############
class UserModelForm(BootStrapModelForm):
# 重新添加效验
name = forms.CharField(min_length=3,
label="用户名",
widget=forms.TextInput(attrs={"class": "form-control"})
)
class Meta:
model = models.User # 获取数据库User类的验证规则
# print("model=",model)
fields = ["name", "password", "age", "account", "create_time", "gender", "depart"] # 获取表头
# print("fields=",fields)
#########modelsForm#######
class PrettyModelForm(BootStrapModelForm):
# 进行格式的校验: 第一种: 字段+正则
from django.core.validators import RegexValidator
mobile = forms.CharField(
label="手机号",
validators=[RegexValidator(r'1[3-9]\d{9}$', '手机号格式错误'), ], # 使用正则效验,不符合提示错误信息
)
class Meta:
model = models.PrettyNum
fields = ["mobile", "price", "level", "status"]
# fields = "__all__" # 所有字段
# exclude = ["level"] # 排除那个字段
# 校验: 第二种:钩子方法, clean_字段名
def clean_mobile(self):
from django.core.validators import ValidationError
txt = self.cleaned_data["mobile"] # self.cleaned_data["字段"]:获取用户传入的数据
exists = models.PrettyNum.objects.filter(mobile=txt).exists() # 判断用户输入的手机号是否已存在
# 验证不通过,抛给前端一个异常
if exists:
raise ValidationError("手机号已存在") # 返回前端异常信息
# 验证通过,把用户输入的值返回
return txt
#####编辑的modelform####3
class PrettyUpdateModelForm(BootStrapModelForm):
# mobile = forms.CharField(disabled=True, label="手机号") # 设置不可更改
from django.core.validators import RegexValidator
mobile = forms.CharField(
label="手机号",
validators=[RegexValidator(r'1[3-9]\d{9}$', '手机号格式错误'), ],
)
class Meta:
model = models.PrettyNum
fields = ["mobile", "price", "level", "status"] # 只显示里面有的数据
# 校验: 第二种:钩子方法, clean_字段名
def clean_mobile(self):
from django.core.validators import ValidationError
# 当前编辑的那一行ID
# print(self.instance.pk) # 固定语法:instance:对象;pk:id
txt = self.cleaned_data["mobile"] # 获取用户传入的数据
exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt).exists() # 判断用户输入的手机号是否已存在
# 验证不通过,抛给前端一个异常
if exists:
raise ValidationError("手机号已jing存在") # 返回前端异常信息
# 验证通过,把用户输入的值返回
return txt