方便之处在于,我们不会再一遍一遍的写form的样式了。

from django import forms

class BootStrapModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BootStrapModelForm, self).__init__(*args, **kwargs)
# 统一给ModelForm生成字段添加样式
for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'

如果还想自定义一些字段不添加样式,那么可以这样写:

class BootStrapModelForm:
exclude_filed_list = [] def __init__(self, *args, **kwargs):
super(BootStrapModelForm, self).__init__(*args, **kwargs)
# 统一给ModelForm生成字段添加样式
for name, field in self.fields.items():
if name in self.exclude_filed_list:
continue
field.widget.attrs['class'] = 'form-control' class CustomerModelForm(BootStrapModelForm, forms.ModelForm):
exclude_filed_list = ['level'] # 不需要添加样式的字段名

思考:无论在使用Form和ModelForm时,想要让页面好看,就需要将每个字段的插件中给他设置form-control样式。

class LevelForm(forms.Form):
title = forms.CharField(
label="标题",
required=True,
# widget=forms.TextInput(attrs={"class": "form-control", 'placeholder': "请输入标题"}),
)
percent = forms.CharField(
label="折扣",
required=True,
help_text="填入0-100整数表示百分比,例如:90,表示90%"
) def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs) # {'title':对象,"percent":对象}
for name,field in self.fields.items():
field.widget.attrs['class'] = "form-control"
field.widget.attrs['placeholder'] = "请输入{}".format(field.label)
class LevelModelForm(forms.ModelForm):
class Meta:
model = models.Level
fields = ['title', 'percent'] def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs) # {'title':对象,"percent":对象}
for name,field in self.fields.items():
field.widget.attrs['class'] = "form-control"
field.widget.attrs['placeholder'] = "请输入{}".format(field.label)

最新文章

  1. react 和 ractive的区别
  2. css体验优化之图片容器设置宽高比
  3. HttpServletRequest的Attribute和Parameter区别
  4. 「Mobile Testing Summit China 2016」 中国移动互联网测试大会-议题征集
  5. 给UILabel设置不同的字体和颜色
  6. Volatile vs VolatileRead/Write?
  7. R command
  8. coursera普林斯顿算法课part1里Programming Assignment 2最后的extra challenge
  9. JS页面跳转的常用方法整理.
  10. linux route 路由设置小记
  11. MAMP显示文件列表
  12. myeclipse maven tomcat插件 创建web工程
  13. Nmap小技巧——探测大网络空间中的存活主机
  14. 根据ul的class和li的class获取li的value值
  15. [PA2014]Bohater
  16. HTTP1.1协议-RFC2616-中文版
  17. 调用sklearn包中的PLA算法[转载]
  18. Java中ArrayList和LinkedList区别 时间复杂度 与空间复杂度
  19. [日常] Redis基本使用测试
  20. NPOI-Excel系列-1000.创建一个标准的Excel文件

热门文章

  1. ubuntu18.04系统下RealTek RTL 8852BE网卡没有WiFi驱动
  2. .Net最小工作线程对应用程序性能的影响
  3. docker中安装elasticsarch 等镜像
  4. 使用 EMQX Cloud 桥接数据到 GCP Pub/Sub
  5. JAVA格式化数字字符串,如手机号,银行卡号的格式化
  6. UI动画 - CATransaction
  7. saml login的流程
  8. ubuntu22.04 交叉编译openwrt
  9. 权昌TSC条码打印机终极使用教程与开发版本代码大全
  10. js数组的创建、添加、删除、获取指定元素下标