简体   繁体   中英

Django Multiple Choice Form with Parent Categories

I have a simple model that looks like this:

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:

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:

  • Lower East Side
  • Times Square
  • East Village
  • West Village
  • ...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.

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. 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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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