【问题标题】:Django prepopulate non-model formsetDjango 预填充非模型表单集
【发布时间】:2013-05-29 14:03:52
【问题描述】:

我的“添加”视图中有以下表单集。用户可以动态添加表单并且添加/保存它们可以完美地工作。现在的问题是我想不出一个好方法来预填充这个表单集以进行编辑。处于编辑状态的用户应该能够在表单集中添加和删除表单。

查看

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))

【问题讨论】:

标签: python django django-forms django-views


【解决方案1】:

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

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

为清晰起见进行了编辑。

【讨论】:

  • 不是我想要的,但我会接受它作为答案,因为我想不出更好的解决方案。
猜你喜欢
  • 2010-10-30
  • 1970-01-01
  • 2014-02-14
  • 2020-11-26
  • 2022-01-01
  • 2012-07-20
  • 1970-01-01
  • 2015-09-02
  • 2012-08-14
相关资源
最近更新 更多