Django预填充非模型形式

2024-10-01 09:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在“添加”视图中有以下表单集。用户可以动态地添加表单,添加/保存表单的效果非常好。现在的问题是我无法找到一个好的方法来预先填充这个表单集进行编辑。在“编辑”下,用户应该能够在表单集中添加和删除表单。在

视图

ClassificationFormset = formset_factory(ClassificationForm)
classification_formset = ClassificationFormset(prefix='habitat_fs')

自定义窗体

^{pr2}$

到目前为止,我试图重写init并填充那里的字段。。。在

def __init__(self, *args, **kwargs):
    habitat = kwargs.pop('habitat', None)
    super(ClassificationForm, self).__init__(*args, **kwargs)
    # Populate fields here based on habitat

…但formset_factory不允许我将任何参数传递到表单中。在

ClassificationFormset = formset_factory(ClassificationForm(habitat=habitat_id))

Tags: 用户self视图编辑表单initfactoryargs
1条回答
网友
1楼 · 发布于 2024-10-01 09:39:23

您可以像普通表单一样为每个表单设置初始值。

def some_method(request):
    ClassificationFormset = formset_factory(ClassificationForm)
    classification_formset = ClassificationFormset(prefix='habitat_fs')
    for form in classification_formset:
        form.initial = {"habitat": "some value"}

为清晰起见进行了编辑。

相关问题 更多 >