在form.fields.queryset中使用<optgroup>?

5 投票
2 回答
3417 浏览
提问于 2025-04-15 17:09

是否可以设置一个表单的外键字段的查询集,这样它就能把不同的查询集分开,并在<optgroup>中显示出来?

这是我现在的代码:

views.py

form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name')

在我的模板模型中,有默认的模板和用户创建的模板。我希望它们在<select>框中能够明显区分开来,比如说:

<select>
  <optgroup label="Default Templates">
    <option>Default 1</option>
    <option>Default 2</option>
  </optgroup>
  <optgroup label="User Templates">
    <option>User Template 1</option>
    <option>User Template 2</option>
  </optgroup>
</select>

这样做可以吗?

2 个回答

4

我以前做过的一个方法是,在表单中不使用外键,而是用一个带选项的字符字段

这个带选项的字符字段支持分组选择。你需要把选项写成这样的格式:

('组 1',(('1','选项1'),('2','选项2'))), ('组 2',(('3','选项3'),('4','选项4')))

选项也可以是一个可调用的函数。所以我创建了一个自己的函数,它会遍历模型并生成像上面那样的元组。

10

我通过这个博客上的例子搞明白了这个问题,链接在这里:这个博客

views.py

form.fields['template'].choices = templates_as_choices(request)

def templates_as_choices(request):
    templates = []
    default = []
    user = []
    for template in Template.objects.filter(default=1).order_by('name'):
        default.append([template.id, template.name])

    for template in Template.objects.filter(user=request.user).order_by('name'):
        user.append([template.id, template.name])

    templates.append(['Default Templates', default])
    templates.append(['User Templates', user])

    return templates

撰写回答