Django系列之form渲染表单后css样式丢失

最通用的form写法

我们经常看各大网站上写这样的form写法

class SYSAdminPhysicalForm(forms.ModelForm):
    '''
    this form for idc's admin
    '''
    class Meta:
        model = models.Machinepro
        exclude = ["m_inside_ip","m_outside_ip","order"]

    business_unit = forms.CharField(required=False,label="所属业务",disabled=True,)
    def __init__(self, *args, **kwargs):
        super(SYSAdminPhysicalForm, self).__init__(*args, **kwargs)
        for field_name in self.base_fields:
            field = self.base_fields[field_name]

            if field_name in ["m_ipmi_user","m_ipmi_passwd"]:
                field.widget.attrs.update({'class': 'form-control'})
            else:
                field.widget.attrs.update({'class': 'form-control',"disabled":True})

写完这个form后,你重启django后第一次通过浏览器打开这个form表单,你会发现css样式是丢失的,特别是我那个disabled属性,一旦丢失,别人就可以修改我的表单了,所以后果非常严重。所以需要采取下面的方法来纠正这个bug

方法1:__new__写法

init__是实例初始化执行,那么我们就改成实例化的时候执行,也就是使用__new

    def __new__(cls, *args, **kwargs):
        obj = super(SYSAdminPhysicalForm, cls).__new__(cls,*args, **kwargs)
        for field_name in obj.base_fields:
            field = obj.base_fields[field_name]

            if field_name in ["m_ipmi_user","m_ipmi_passwd"]:
                field.widget.attrs.update({'class': 'form-control'})
            else:
                field.widget.attrs.update({'class': 'form-control',"disabled":True})

方法2:fields 替换掉base_fields

这个最简单了,把base_fields直接用fields替换就解决了

    
    def __init__(self, *args, **kwargs):
        super(SYSAdminPhysicalForm, self).__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields[field_name]

            if field_name in ["m_ipmi_user","m_ipmi_passwd"]:
                field.widget.attrs.update({'class': 'form-control'})
            else:
                field.widget.attrs.update({'class': 'form-control',"disabled":True}) 

任选一种方法后,任凭django重启多少回,不管你第几次打开表单页面,都不会丢失css样式啦!

posted @ 2017-12-22 18:17  温柔易淡  阅读(1766)  评论(0编辑  收藏  举报