django客户管理系统-使用modelform对HTML标签统一添加样式
给HTML标签统一添加class="form-control"
from django import forms from crm import models #创建客户Form类,继承forms.ModelForm class CustomerForm(forms.ModelForm): class Meta: model = models.Customer fields = '__all__' #重写初始化方法 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for filed in self.fields.values(): filed.widget.attrs['class'] = 'form-control'
有一些HTML标签不需要class="form-control"
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for filed in self.fields.values(): #打印type找到不需要添加class的类,然后进行导入 print(filed,type(filed)) #使用isinstance方法判断 if isinstance(filed, MultiSelectFormField): continue filed.widget.attrs['class'] = 'form-control' filed.widget.attrs['autocomplete'] = 'off'