How to pre-populate AutoModelSelect2Field with static data? (django-select2 library)

ajax, django, javascript, jquery-select2, json

Solution

Possible solution is to allow empty search, so there will be some items in list even when there is nothing in search field.

django-select2 view always skips empty term in "get" method, so we need to override it:

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)

Now the "" term will get to "get_results" method of your field:

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)

Problem

I have a field like following: ``` class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget ``` It works fine, but starts loading only after I enter 2 letters, while I'd like it to include the most relevant choices right into html and search over them when user entered only 1 letter. So what approach would you recommend? Is it possible to do that with django-select2 (and obviously select2 itself), or I'd write my own JS functions for that?

Original source