如何将 ChoiceField 选择传递给 formset?

How to pass ChoiceField choices to formset?

这个名字很好用,但我可以想出如何以同样的方式传递选项列表。这些字段为空白。在调试中,选项似乎设置正确。

forms.py

class MatchSheets(forms.Form):
    """ Match sheets """
    name = forms.CharField()
    propertyuser = forms.ChoiceField(choices=(), required=False)


SheetSet = formset_factory(
    MatchSheets,
    extra=0
)

views.py

    sheets = PropSheetNames.objects.filter(owner=request.user,
                                           sponsoruser=sponsoru_id)
    props = SponsorsUsers.objects.filter(owner=request.user,
                                           id=sponsoru_id).all()

    initial_set = []
    choiceset = (((prop.id), (prop.alias)) for prop in props[0].properties_user.all())

    for sh in sheets:
        initial_set.append(
            {'name': sh.name,
             'propertyuser.choices': choiceset}
        )

    form = SheetSet(request.POST or None, initial=initial_set)

我知道有人会指出这可以通过 modelformset_factory 来完成,或者 modelselect 来完成 propertyuser,但我 运行两者都存在问题,而手动操作给了我更大的灵活性。

首先,这是错误的(已更正):

choiceset = [((prop.id), (prop.alias)) for prop in props[0].properties_user.all()]

然后在下面添加这个 form=

for f in form:
        f.fields['propertyuser'].choices = choiceset

能够更进一步,将选项默认为名称字段的值:

    initial_set = []
    nameset = [prop.alias for prop in props[0].properties_user.all()]
    choiceset = [((prop.alias), (prop.alias)) for prop in props[0].properties_user.all()]
    choiceset.append(('', '----'))

然后

    for f in form:
        f.fields['propertyuser'].choices = choiceset
        if f.initial['name'] is not None and f.initial['name'] in nameset:
            f.fields['propertyuser'].initial = f.initial['name']

现在用户只需要处理不匹配的对,就完成了。这些是我被迫放弃使用模型选项的原因,至少在我的能力水平上是这样。