Python 3.x 如何将ChoiceField选项传递给formset?

Python 3.x 如何将ChoiceField选项传递给formset?,python-3.x,django-forms,django-views,django-2.2,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( Mat

这个名字很好用,但我可以用同样的方法计算出如何传递选择列表。这些字段是空白的。在调试中,选项显示为正确设置

forms.py

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


SheetSet = formset_factory(
    MatchSheets,
    extra=0
)
    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)
视图.py

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


SheetSet = formset_factory(
    MatchSheets,
    extra=0
)
    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\u工厂
,或者对于
propertyuser
,使用
modelselect
可以做得更好,但我在这两个方面都遇到了问题,手动操作给了我更多的灵活性

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

然后将此添加到下面的
form=

for f in form:
        f.fields['propertyuser'].choices = choiceset
能够更进一步,将选项也默认为name字段的值:

    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']
现在,用户只需要处理不匹配的对,就可以了。这就是我被挤出使用模型选项的原因,至少在我的能力水平上是这样