Collapsible ChoiceField in Django

359 Views Asked by At

I have a django form with what is currently a TextField input that I'd like to turn into a ChoiceField so that I can do away with having to compare similar answers to determine if they refer to the same thing. However, the number of possible choice is prohibitive (several hundred). What I really would like is a collapsible ChoiceField where users could select a category, then a sub-category, and so on so that at each step they would only be presented with a reasonable number of options (especially since many users are on mobile devices with limited screen sizes). The options are quite amenable to unambiguous categorization and so this seems like a good way to display the information. However, while I see information about collapsing all sorts of other sorts of aspects of forms I haven't seen how to do this. I'm not even sure what avenue to pursue to make this work best. CSS or javascript seem to be the ways most people make collapsible lists but I don't know whether either of these will play well with a django Select widget. What's my best option to do this sort of thing?

Here are the options I'm aware of: 1) Write some sort of new widget. This sounds horrible (based on my experience writing new widgets) but if it's the best option I'll do it. 2) Use a normal select widget and use javascript to hide options. I'm not exactly sure how to select options in clean groups though. 3) Use a CSS collapsible list and and hidden form field with a bit of javascript to grab the value from the list and insert it into the hidden field. 4) Use a chain of views to navigate through to the smallest category. This sounds easy to do, nice and clean (because all the logic is in Python where I feel comfortable), but requires multiple reloads which may be problematic for mobile users.

1

There are 1 best solutions below

3
On

If the number of subcategories is infinite, this is probably your only solution. If it's not infinite, you might be able to get away with loading up all of the choices on the page immediately along with their parent categories so that you can decide which choices to show via javascript.