8

Suppose I have a form field as below:

admin = forms.ModelChoiceField(queryset=Profile.objects.all(),
    help_text=_('select an admin for this organization'),
    label=_('Organization Admin'),
)

when this form is rendered in a template and I can see a drop-down button on that field and can select an item.

But the number of items is so much that it is very difficult for me to select one.

I want a search option just on top of the drop-down list.

Is it possible? If possible, how?

cjahangir
  • 1,773
  • 18
  • 27

2 Answers2

3

Part from my code:

from django.contrib.admin.widgets import FilteredSelectMultiple

class WorkForm(forms.Form):
    materials = forms.ModelMultipleChoiceField(label=_('Materials'), queryset=Goods.objects.filter(deleted=False), required=False, widget=FilteredSelectMultiple(_('materials'), True))

    class Media:
        css = {
                'all': (
                          '/static/admin/css/widgets.css',
                          '/static/css/widgets.css',
                       )
              }
        js = [
                '/admin/jsi18n/'
             ]

Or you can use https://github.com/applegrew/django-select2

Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39
  • The widget cannot be loaded with new forms added via JS. Could you help show me how? `$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));` – Dingkun Liu Feb 11 '20 at 08:59
  • Where can i get `widgets.css` and relevant `js` defined on class `Media` – Kenneth mwangi Feb 18 '22 at 20:16
1

This django plugin is quite helpful: https://pypi.python.org/pypi/django-simple-autocomplete/

It works with jQuery, so you have to ensure that jQuery is working. You have just follow the four installation steps and adapt your form model.

Hope this helps.

zypro
  • 1,158
  • 3
  • 12
  • 33