Search code examples
djangodjango-modelsdjango-formsdjango-autocomplete-light

autocomplete_light is not showing correct suggestions with choice_for_request


I have autocomplete-light in the django modal form. I wanted to apply dynamic filtering in the suggestion box, that's why I have used choice_for_request() in the autocompletebasemodel. But because of using choice_for_request(), the suggestions are not according to the keyword typed but all the values that can be entered.

This is my form:

class CamenuForm(autocomplete_light.ModelForm):
  class Meta:
    model = Ca_dispensaries_item
    exclude = ('dispensary',)
    autocomplete_fields = ('item',)

  def __init__(self, *args, **kwargs):
    self.category = kwargs.pop('category', None)
    super(CamenuForm, self).__init__(*args, **kwargs)
    self.fields['item'].queryset=Items.objects.filter(product_type__name=self.category)

This is the registry and the class:

autocomplete_light.register(Items, AutoComplete )

class:

class AutoComplete(autocomplete_light.AutocompleteModelBase):
    search_fields=('item_name',)
    def choices_for_request(self):
      category = self.request.session.get('category','')
      if category:
        choices = Items.objects.filter(product_type__name=category)
      return self.order_choices(choices)[0:self.limit_choices]  

I really dont know what changes to make in changes_for_request so as to make it work correctly


Solution

  • After going through various documents, the solution which worked as correctly as it should be is

    def choices_for_request(self):
        category = self.request.session.get('category','')
        item=self.request.GET.get('q','')
        choices = self.choices.all()
        if item:
            choices = choices.filter(item_name__icontains=item)
        super(AutoComplete, self).choices_for_request()
        if category:
            choices = choices.filter(product_type__name=category)
        return self.order_choices(choices)[0:self.limit_choices]  
    

    I missed out

    item=self.request.GET.get('q','')
    

    autocomplete-light uses the get method and the predefined literal q to transfer the value typed by user. I wasn't able to crack out the meaning of q. After some hit and trial, I got that it is used to store the user given value in suggestion box.