How to group the choices in a Django Select widget?

前端 未结 3 1419
挽巷
挽巷 2020-12-13 10:18

Is it possible to created named choice groups in a Django select (dropdown) widget, when that widget is on a form that is auto-generated from a data Model?

3条回答
  •  无人及你
    2020-12-13 10:47

    After a quick look at the ModelChoiceField code in django.forms.models, I'd say try extending that class and override its choice property.

    Set up the property to return a custom iterator, based on the orignial ModelChoiceIterator in the same module (which returns the tuple you're having trouble with) - a new GroupedModelChoiceIterator or some such.

    I'm going to have to leave the figuring out of exactly how to write that iterator to you, but my guess is you just need to get it returning a tuple of tuples in a custom manner, instead of the default setup.

    Happy to reply to comments, as I'm pretty sure this answer needs a little fine tuning :)

    EDIT BELOW

    Just had a thought and checked djangosnippets, turns out someone's done just this: ModelChoiceField with optiongroups. It's a year old, so it might need some tweaks to work with the latest django, but it's exactly what I was thinking.

提交回复
热议问题