56

The Django admin site makes use of a really cool widget:

enter image description here

How can I make use of this widget in my own applications? I don't see anything like that listed here.

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

58

From the docs:

The Django Admin application defines a number of customized widgets for calendars, filtered selections, and so on. These widgets define media requirements, and the Django Admin uses the custom widgets in place of the Django defaults. The Admin templates will only include those media files that are required to render the widgets on any given page.

If you like the widgets that the Django Admin application uses, feel free to use them in your own application! They’re all stored in django.contrib.admin.widgets.

In this case, you want the FilteredSelectMultiple widget. To use it, apply the widget on a form field like so:

my_field = forms.ModelMultipleChoiceField(queryset=MyModel.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False))

Make sure to include the forms media in the template as it needs to include a few JS files.

Community
  • 1
  • 1
Bartek
  • 15,269
  • 2
  • 58
  • 65
  • Hrm... doesn't want to work for some reason. All the JS is there, but it isn't converting the selectbox for some reason. http://7src.com/~mnb2/a3/access – mpen Nov 09 '09 at 01:12
  • This is a wild guess but try setting your second argument (for the `is_stacked` variable) to False. Looking at the code, it looks like that may affect the display of two boxes or not. Unfortunately I can't test it myself right now so I'm just looking through code hehe :) – Bartek Nov 09 '09 at 01:29
  • 2
    Nevermind. Found the problem. It needs `` as well, which isn't included by `form.media`. – mpen Nov 09 '09 at 01:29
  • 4
    Oh, I should also mention that you need to be logged in as a superuser just to access that file!! I recommend saving the file out and including that instead. – mpen Nov 11 '09 at 21:40
  • @mpen, what exactly is located in ``? Any reason why it's not pointing to a specific `.js` file? – NickBraunagel Apr 14 '17 at 17:55
  • @NickBraunagel I wrote that like 8 years ago now. It does seem weird that that doesn't end with `.js`. I must have copied it off the Django admin site though. – mpen Apr 15 '17 at 18:14