可能的解决方案是允许空搜索,因此即使搜索字段中没有任何内容,列表中也会有一些项目。
django-select2 视图总是在“get”方法中跳过空词,所以我们需要覆盖它:
class MySelect2ResponseView(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(MySelect2ResponseView, self).get(request, *args, **kwargs)
现在“”术语将进入您的领域的“get_results”方法:
class ContactSelectWidget(AutoHeavySelect2Widget):
def __init__(self, *args, **kwargs):
kwargs['select2_options'] = {
# this will allow select2 to send empty search to server
'minimumInputLength': 0,
# it's needed, otherwise search field will be hided by select2
'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 anything you want here:
return ('nil', False, [(1, "my_item1", {}), (2, "my_item2", {})])
else:
return super(ContactSelect, self).get_results(request, term, page, context)