Skip to main content
 首页 » 编程设计

python之如何将 optgroups 添加到 django ModelMultipleChoiceField

2025年05月04日30lyhabc

我有一个带有 ModelMultipleChoiceField 的表单来列出类别。 我想使用 Category.group 字段对类别进行分组。

我认为通过更改 field.choices 在 init 函数中它会成功

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 仍然会删除 __init__ 函数中设置的 self.choices 信息。

我怎样才能以正确的方式做到这一点?

请您参考如下方法:

实际上它就像我刚刚解释的那样工作,但不要忘记那部分:

class ProfilForm(ModelForm): 
    categories  = CategoriesField(queryset=Category.objects.all().order_by('group'), label=_(u'Catégories'))