22 BootStrapModelForm

方便之处在于,我们不会再一遍一遍的写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)
posted @ 2022-09-01 15:45  角角边  Views(113)  Comments(0Edit  收藏  举报