简体   繁体   English

Django 父类别选择题

[英]Django Multiple Choice Form with Parent Categories

I have a simple model that looks like this:我有一个简单的 model,如下所示:

class Neighborhood(models.Model):
    name = models.CharField(max_length=255)
    borough = models.ForeignKey(Borough)

    def __unicode__(self):
        return self.name

In my forms.py file, I have a simple form being rendered with the options:在我的 forms.py 文件中,我有一个使用以下选项呈现的简单表单:

class SearchForm(forms.Form):
    neighborhood = forms.ModelMultipleChoiceField(required=False, queryset=Neighborhood.objects.all(), widget=CheckboxSelectMultiple())

This is fine and lists out all the options in my Neighborhood model. It looks something like this:这很好,并列出了我的邻居 model 中的所有选项。它看起来像这样:

  • Lower East Side下东区
  • Times Square时代广场
  • East Village东村
  • West Village西村
  • ...etc ...ETC

    However, I would like to list the parent category of the neighborhood, in this case the borough.但是,我想列出社区的父类别,在本例中是自治市镇。 The desired look would be like this:所需的外观将是这样的:

  • Brooklyn布鲁克林

    • Williamsburg威廉斯堡
    • DUMBO小飞象
    • ... ...
  • Manhattan曼哈顿
    • Lower East Side下东区
    • Times Square时代广场
    • West Village西村
    • East Village东村
  • Queens皇后区
    • ... ...

I've tried to call the two different objects and combine them into a custom list, however I'm not able to pass that through the queryset as it gave me an AttributeError for not having 'all' available.我试图调用这两个不同的对象并将它们组合到一个自定义列表中,但是我无法通过查询集传递它,因为它给了我一个 AttributeError 因为没有“全部”可用。

Is there another way to do this?还有另一种方法吗?

The best way, I think, is to write custom form widget for it.我认为最好的方法是为其编写自定义表单小部件。

Simple (and not bad too) way is to output <select> tag in template manually.简单(也不错)的方法是手动在模板中添加 output <select>标签。 regroup filter will do all the job.重组过滤器将完成所有工作。

For future people going down the same path:对于未来走同样道路的人:

I found this link where it explains how to do it by creating a custom ModelChoiceIterator (the class responsible for making the choices tuple for choice fields) and making it include the parent category.我找到了这个链接,它解释了如何通过创建自定义 ModelChoiceIterator(class 负责为选择字段制作选择元组)并使其包含父类别来做到这一点。

PS The author creates a new ModelChoiceField that uses the new iterator, but I believe you can now simply set a custom iterator using the iterator argument of both ModelChoiceField and ModelMultipleChoiceField ( link to docs ) PS 作者创建了一个使用新迭代器的新 ModelChoiceField,但我相信您现在可以使用 ModelChoiceField 和 ModelMultipleChoiceField 的迭代器参数简单地设置自定义迭代器( 文档链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM