Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching with ModelChoiceField in django

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?

like image 369
cjahangir Avatar asked Mar 31 '16 07:03

cjahangir


2 Answers

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

like image 198
Sergey Gornostaev Avatar answered Nov 15 '22 03:11

Sergey Gornostaev


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.

like image 21
zypro Avatar answered Nov 15 '22 03:11

zypro