作者:徐毛毛的大猫儿 | 来源:互联网 | 2022-12-10 14:23
我有一个完全不同的json配置的平台.任何用户都可以创建一个完全不同的新json配置.因此,我不能静态地模拟这个.
我试图为这些json配置制作动态表单.
一些json配置具有值或对象的数组.在视觉上,我将需要这些是一个带有"添加更多"按钮的输入列表.
我发现这formsets
是在django表单中添加值数组的普遍接受的方法.(我已经在使用mysql所以我无法切换到postgres ArrayField).但是,从django示例中,多个formset分别初始化并传递到视图中.
由于我的配置是动态的,我不知道要初始化什么表格集,而且字段的顺序在表单集和表单之间混合.
例如,我遵循此链接并动态创建我的表单类,如下所示:
class FieldHandler():
def __init__(self, fields):
self.formfields = {}
for field in fields:
optiOns= self.get_options(field)
f = getattr(self, "create_field_for_" +
field['type'])(field, options)
self.formfields[field['name']] = f
def get_options(self, field):
optiOns= {}
options['label'] = field['name']
options['help_text'] = field.get("help_text", None)
options['required'] = bool(field.get("required", 0))
return options
def create_field_for_text(self, field, options):
options['max_length'] = int(field.get("max_length", "20"))
return django.forms.CharField(**options)
def create_field_for_number(self, field, options):
options['max_value'] = int(field.get("max_value", "999999999"))
options['min_value'] = int(field.get("min_value", "-999999999"))
return django.forms.IntegerField(**options)
# This does not work, formsets are not shown in the template
def create_field_for_array(self, field, options):
fh = FieldHandler(field['elements'])
form_class = type('DynamicForm', (django.forms.Form,), fh.formfields)
DynamicFormSet = formset_factory(form_class)
return DynamicFormSet(prefix=field['name'])
并在视图中:
# arg to FieldHandler is an example config, it will be retrieved from db
fh = FieldHandler([
{'type': 'text', 'label': 'position'},
{'type': 'array', 'label': 'calendar', 'elements': [
{'type': 'text', 'label': 'country'},
{'type': 'text', 'label': 'url'},
]},
{'type': 'number', 'label': 'maxSize'}
])
form_class = type('DynamicForm', (django.forms.Form,), fh.formfields)
form = form_class(request.POST or None)
如您所见,动态表单初始化为配置position
,calendar
元素数组和maxSize
字段.
我的问题是我的动态formset根本没有显示在视图中.如果我要分离表单集,我会以某种方式将其插入原始表单中的某个位置,因此我不能只迭代字段,并动态创建第form
一个,然后formsets
从数组字段动态创建.
因此,我希望有一种方法来动态创建这种类型的表单,其中表单中的某些字段是formsets
.
我该怎么做呢?或者我应该如何处理?