如何将ChoiceField选项传递给表单集?

时间:2019-12-04 19:20:45

标签: python-3.x django-forms django-views django-2.2

这个名字很好用,但是我可以弄清楚如何以相同的方式传递选择列表。这些字段变为空白。在调试中,选项显示正确。

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,但是我遇到了两者都存在的问题,手动执行此操作使我更具灵活性。

1 个答案:

答案 0 :(得分:0)

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

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']

现在,用户只需要处理不匹配的对就可以了。这就是我被淘汰使用模型选项的原因,至少在我的能力水平上。