我创建了一个包含多个动态字段(没有类属性)的表单,这些字段在self.fields
函数中添加到__init__
,如下所示:
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
时Form不知道字段,因此我不知道如何手动加载字段。想法?
答案 0 :(得分:1)
您可以在致电base_fields
super
:
__init__
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)
答案 1 :(得分:0)
对我来说,只需从Form
类设置数据属性,类似于__init__
类的Form
函数。此外,必须将is_bound
属性设置为通过is_valid()
方法验证表单:
class CustomForm(django.forms.Form):
def __init__(dynamic_fields, data=None, *args, **kwargs):
super(CustomForm, self).__init__(*args, **kwargs)
for name, field in dynamic_fields.items():
self.fields[name] = field
self.is_bound = data is not None
self.data = data or {}
但我不太确定,如果这是正确的解决方法?!