Python 如何将optgroups添加到django ModelMultipleChiceField?
我有一个带有Python 如何将optgroups添加到django ModelMultipleChiceField?,python,django,django-forms,properties,Python,Django,Django Forms,Properties,我有一个带有modelmultipechoicefield的表单来列出类别。 我想使用Category.group字段对类别进行分组 我认为,通过更改init函数中的字段。选项,它将成功 class CategoriesField(forms.ModelMultipleChoiceField): def __init__(self, queryset, **kwargs): super(forms.ModelMultipleChoiceField, self).__ini
modelmultipechoicefield
的表单来列出类别。
我想使用Category.group
字段对类别进行分组
我认为,通过更改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
但是modelcooceiterator
仍然会删除在\uuuu init\uuu
函数中设置的self.choices
信息
我怎样才能正确地做到这一点呢?事实上,它就像我刚才解释的那样工作,但不要忘记这一部分:
class ProfilForm(ModelForm):
categories = CategoriesField(queryset=Category.objects.all().order_by('group'), label=_(u'Catégories'))
我发现这个问题/答案很有帮助,但代码改变了很多。上面代码的问题是,它只生成一次列表,然后缓存它(queryset只使用一次)。我的代码是为“profile”(又名author)排序的“Article”对象编写的,但任何人都应该能够修改它以供使用。它每次都使用一个新的查询集,因此不需要重新启动就可以更新它(除非您将
cache\u choices=True
传递给articleMultipechoicefield
,然后缓存它)
你的代码为我工作,谢谢!也可以与models.ManyToManyField一起使用,其他人可能也会感兴趣:
from django.db import models
class CustomManyToManyField(models.ManyToManyField):
def formfield(self, *args, **kwargs):
kwargs["form_class"] = CategoriesField
return super().formfield(**kwargs)
我也有同样的缓存错误,并且通过将整个选项更新放在迭代器中修复了它:
class CustomModelChoiceIterator(forms.models.ModelChoiceIterator):
def __iter__(self):
group = ""
subgroup = []
for category in self.queryset:
if not group:
group = category.group
if group != category.group:
yield (group.title, subgroup)
group = category.group
subgroup = [(category.id, category.name)]
else:
subgroup.append((category.id, category.name))
yield (group.title, subgroup)
class CategoriesField(forms.ModelMultipleChoiceField):
iterator = CustomModelChoiceIterator
class CustomModelChoiceIterator(forms.models.ModelChoiceIterator):
def __iter__(self):
group = ""
subgroup = []
for category in self.queryset:
if not group:
group = category.group
if group != category.group:
yield (group.title, subgroup)
group = category.group
subgroup = [(category.id, category.name)]
else:
subgroup.append((category.id, category.name))
yield (group.title, subgroup)
class CategoriesField(forms.ModelMultipleChoiceField):
iterator = CustomModelChoiceIterator