Django multi-select widget?

2020-01-25 13:02发布

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.

1条回答
戒情不戒烟
2楼-- · 2020-01-25 13:28

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.

查看更多
登录 后发表回答