Django预填充非模型formset

时间:2013-05-29 14:03:53

标签: python django django-forms django-views

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

视图

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

自定义表单

class ClassificationForm(forms.Form):

classification = ClassificationField(
    label=_('Habitat Classification'),
    required=False,
    queryset=Classification.objects.all(),
)

community = CommunityField(
    label=_('Community'),
    required=False,
    queryset=Community.objects.none(),
)

def save(self, habitat_id, *args, **kwargs):
    data = self.cleaned_data
    if data:
        habitat_community = Habitat_Community()
        habitat_community.habitat = habitat_id
        habitat_community.community = data['community']
        habitat_community.save()

到目前为止,我已尝试覆盖 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))

1 个答案:

答案 0 :(得分:0)

您可以像普通表单一样为每个表单设置首字母。

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

编辑清晰。