【问题标题】:How to pass ChoiceField choices to formset?如何将 ChoiceField 选项传递给表单集?
【发布时间】:2020-03-29 16:27:13
【问题描述】:

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

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,但我遇到了这两个问题,只是手动操作给了我更多灵活性。

【问题讨论】:

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


    【解决方案1】:

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

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

    然后在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']
    

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

    【讨论】:

      猜你喜欢
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2012-08-12
      • 1970-01-01
      • 2014-10-11
      • 2018-11-29
      • 1970-01-01
      相关资源
      最近更新 更多