为了方便管理,我们在/app01/utils下新建bootstrap.py
from django import forms class BootStrapModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 循环找到所有的插件,添加class = "form-control"样式 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 }
在视图函数views.py文件中导入我们编写的BootStrapModelForm类
from app01.utils.bootstrap import BootStrapModelForm
我们在视图函数中编写的ModelForm类,就可以直接继承BootStrapModelForm,实现为ModelForm自动生成的input框添加BootStrap样式
class UserModelForm(BootStrapModelForm): # 设置更多校验,用户名至少为三个字符 name = forms.CharField(min_length=3, label="用户名") class Meta: model = models.UserInfo fields = ["name", "password", "age", "acount", "creata_time", "gender", "depart"]
标签:widget,BootStrapModelForm,BootStrap,field,attrs,input,ModelForm,class From: https://www.cnblogs.com/kekeeleven/p/17773965.html