One solution could be to allow for an empty search field, ensuring that there are items in the list even when no search criteria is entered.
The django-select2 view typically skips over empty terms in the "get" method, so it may be necessary to override this behavior:
class CustomSelect2ResponseView(AutoResponseView):
def get(self, request, *args, **kwargs):
term = request.GET.get('term')
if term == "":
return self.render_to_response(self._results_to_context(self.get_results(request, term, -1, None)))
return super(CustomSelect2ResponseView, self).get(request, *args, **kwargs)
By implementing this change, the empty term will now be passed to the "get_results" method of your field:
class ContactSelectWidget(AutoHeavySelect2Widget):
def __init__(self, *args, **kwargs):
kwargs['select2_options'] = {
'minimumInputLength': 0,
'minimumResultsForSearch': 0,
}
super(ContactSelectWidget, self).__init__(*args, **kwargs)
class ContactSelect(AutoModelSelect2Field):
widget = ContactSelectWidget
queryset = Contact.objects.all()
search_fields = ['name__contains']
to_field = 'name'
def get_results(self, request, term, page, context):
if term == "":
return ('nil', False, [(1, "my_item1", {}), (2, "my_item2", {})])
else:
return super(ContactSelect, self).get_results(request, term, page, context)