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

how to create a dependant drop down using autocomplete light


I have created a form using Django Model Form and autocomplete_light. I want to filter the suggestions in the drop down list item according to the arguement passed when the class is called.

My form is

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)

I have applied a filter in __init__ according to the value of category passed but it doesnot seems to work.

The registry is

autocomplete_light.register(Items,search_fields=('item_name',))

And the form is called as

form = CamenuForm(request.POST or None, category=category)

Please suggest me a way so that I can refine the search based on the value passed while calling form.

I have tried to modify it by using

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

and registry as autocomplete_light.register(Items, AutoComplete ) Through this, I get to know that category gets the value none (because of the default value I chose) and this method also doesnt seems to work.

IS there a way that the value of category can be passed to request_for_choices so that the serach can be refined?


Solution

  • The self.request.POST (or self.request.GET) QueryDict of an Autocomplete class will not contain any more information than the search query because they are not passed when the view is created (so self.request.POST.get('category', 'none') will always return 'none').

    So the difficult part is to somehow pass an argument (category) to a completely different view. This could be done, for instance by modifying the javascript that calls the autocomplete. Meaning, you'll need to change getQuery (http://django-autocomplete-light.readthedocs.org/en/stable-2.x.x/script.html#override-autocomplete-js-methods) to append category=foo to the url that is called and then, at choices_for_request read the self.request.GET QueryDictto get that value.

    Another way to do it is to put the category parameter to your session and then read the session in the choices_for_request. For example, on the __init__ of your view you'll do something like self.request.session['category'] = 'foo' and on the choices_for_request you'll get that value.