Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Django中将动态添加的字段保存到模型中的表单?_Django_Django Models_Django Forms - Fatal编程技术网

如何在Django中将动态添加的字段保存到模型中的表单?

如何在Django中将动态添加的字段保存到模型中的表单?,django,django-models,django-forms,Django,Django Models,Django Forms,当用户单击按钮时,我需要向ModelForm添加新字段,我通过重写init方法来实现这一点 def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) super(Form, self).__init__(*args, **kwargs) self.fields['extra_field_count'].initial = extra_fields for index in

当用户单击按钮时,我需要向ModelForm添加新字段,我通过重写init方法来实现这一点

def __init__(self, *args, **kwargs):
    extra_fields = kwargs.pop('extra', 0)
    super(Form, self).__init__(*args, **kwargs)
    self.fields['extra_field_count'].initial = extra_fields
    for index in range(int(extra_fields)):
        print('loop')
        # generate extra fields in the number specified via extra_fields
        self.fields['extra_field_{index}'.format(index=index)] = \
            forms.CharField()
这似乎是可行的,因为我没有收到任何错误,表单是有效的,但我现在想知道如何将附加字段保存到我的模型中