【django學習-24】自定義外掛

Tony_xiao發表於2024-05-14
  • 1.ModelForm可以幫助我們生成HTML標籤,這種是普通的標籤
class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ["name", "password",]

form = UserModelForm()
  • 2.如果我們要使用bootstrap的標籤,該怎麼操作呢?
    • 2.1:自定義外掛
class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ["name", "password",]
        widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
            "password": forms.PasswordInput(attrs={"class": "form-control"}),
            "age": forms.TextInput(attrs={"class": "form-control"}),
        }
  • 2.2:上述方法,要對每個欄位進行修改,不利於開發。如是,我們可以利用下面的方法批次修改
class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age",]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # 迴圈ModelForm中的所有欄位,給每個欄位的外掛設定
        for name, field in self.fields.items():
            # 欄位中有屬性,保留原來的屬性,沒有屬性,才增加。
            if field.widget.attrs:
				field.widget.attrs["class"] = "form-control"
				field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control", 
                    "placeholder": field.label
                }

相關文章