Django:使用动态字段加载表单

时间:2017-10-13 12:34:37

标签: python django forms

我创建了一个包含多个动态字段(没有类属性)的表单,这些字段在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不知道字段,因此我不知道如何手动加载字段。想法?

2 个答案:

答案 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 {}

但我不太确定,如果这是正确的解决方法?!