The most common form notation
We often look at the major websites to write this 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})
After writing this form, after you restart Django for the first time through the browser to open the form form, you will find that the CSS style is missing, especially my disabled property, once lost, others can modify my form, so the consequences are very serious. So we need to take the following approach to correct this bug
Method 1:__new__ notation
__INIT__ is an instance initialization execution, then we are going to do it when we instantiate it, that is, using the 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})
Method 2:fields Replace Base_fields
This is the simplest, to replace the base_fields directly with fields to solve the
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:
If you choose a method, let Django restart how many times, no matter how often you open the form page, no loss of CSS style!
CSS styles are missing after the form of the Django series is rendered