如何将optgroup添加到Django ModelMultipleChoiceField? [英] How to add optgroups to a django ModelMultipleChoiceField?
本文介绍了如何将optgroup添加到Django ModelMultipleChoiceField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有 ModelMultipleChoiceField
的表格来列出类别。
我想使用 Category.group
字段对类别进行分组。
I have a form with a ModelMultipleChoiceField
to list of categories.
I would like to group categories using the Category.group
field.
我认为通过更改该字段。在init函数中选择
会达到目的
I thought that by changing the field.choices
in the init function it will make the trick
class CategoriesField(forms.ModelMultipleChoiceField):
def __init__(self, queryset, **kwargs):
super(forms.ModelMultipleChoiceField, self).__init__(queryset, **kwargs)
self.queryset = queryset.select_related()
self.to_field_name=None
group = None
list = []
self.choices = []
for category in queryset:
if not group:
group = category.group
if group != category.group:
self.choices.append((group.title, list))
group = category.group
list = [(category.id, category.name)]
else:
list.append((category.id, category.name))
try:
self.choices.append((group.title, list))
except:
pass
但是 ModelChoiceIterator
仍会删除 self.choices
在 __ init __
函数中设置的信息。
But the ModelChoiceIterator
still erase the self.choices
info that are set in the __init__
function.
如何正确执行此操作
推荐答案
实际上它的工作方式就像我刚才解释的那样,但是请不要忘记该部分:
Actually it is working like I just explain but dont forget that part :
class ProfilForm(ModelForm):
categories = CategoriesField(queryset=Category.objects.all().order_by('group'), label=_(u'Catégories'))
这篇关于如何将optgroup添加到Django ModelMultipleChoiceField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文