我創建了被添加到self.fields
在__init__
功能這樣的多個動態域(無級屬性)形式負載形式:Django的:用動態字段
class CustomForm(django.forms.Form):
def __init__(dynamic_fields, *args, **kwargs):
super(CustomForm, self).__init__(*args, **kwargs)
for name, field in dynamic_fields.items():
self.fields[name] = field
dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()}
CustomForm(dynamic_fields)
現在,我不知道該怎麼在請求POST
之後加載表單。通常情況下,我會做這樣的事情:
custom_form = CustomForm(request.POST)
if custom_form.is_valid():
data = custom_form.cleaned_data
...
但作爲字段不知道表單時super
被調用時,我不知道如何加載領域之後手動。想法?
class CustomForm(django.forms.Form):
def __init__(dynamic_fields, *args, **kwargs):
self.base_fields.update(dynamic_fields)
super(CustomForm, self).__init__(*args, **kwargs)
dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()}
CustomForm(dynamic_fields)
是字段鍵總是指向相同的字段類型? – grrrrrr
不,字段類型可以是每個有效的django字段類型 – Henhuy