[英]How can I extend a Django Form class?
我想基於這個創建多個類似的 forms:
class DatabaseForm(forms.Form):
label = "Database label" # This does not work, but I also can't define it in __init__ method, as I can't access self below in "name" field
name = forms.BooleanField(label=label, required=False)
username = forms.CharField(label="Username", required=False)
password = forms.CharField(label="Password", required=False)
我只更改label,如下所示:
class MySQLForm(DatabaseForm):
label = "MySQL" # Somehow override label of super class
我怎樣才能做到這一點?
您可以在__init__
構造函數中覆蓋 label:
class MySQLForm(DatabaseForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].label = 'MySQL'
您還可以在DatabaseForm
中使用參數:
class DatabaseForm(forms.Form):
name_label = 'Database label'
name = forms.BooleanField(label=None, required=False)
username = forms.CharField(label='Username', required=False)
password = forms.CharField(label='Password', required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].label = self.name_label
class MySQLForm(DatabaseForm):
name_label = 'MySQL'
您可以在__init__
中設置字段 label 並通過self.label
訪問 class 屬性
class DatabaseForm(forms.Form):
label = "Database label"
name = forms.BooleanField(required=False)
username = forms.CharField(label="Username", required=False)
password = forms.CharField(label="Password", required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].label = self.label
class MySQLForm(DatabaseForm):
label = "MySQL"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.