How to create a dependent drop using autocomplete
I created a form with Django Model Form
and autocomplete_light
. I want to filter the suggestions in the dropdown item
according to the argument passed when calling the class.
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)
I applied the filter __init__
according to the passed value category
, but it doesn't seem to work.
Registry
autocomplete_light.register(Items,search_fields=('item_name',))
And the form is called
form = CamenuForm(request.POST or None, category=category)
Please suggest a way for me so that I can refine the search based on the value passed in when the form was called.
I tried to change it 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 the registry as autocomplete_light.register (Items, autocomplete) Thanks to this, I know that the category gets the value none
(due to the default value I chose) and this method also doesn't work.
Is there a way that the value category
can be passed to request_for_choices
so that serach can be refined?
source to share
self.request.POST
(or self.request.GET
) QueryDict
the Autocomplete class will not contain more information than the search query, since they are not passed when the view is created (so self.request.POST.get('category', 'none')
it will always return 'none'
).
So the tricky part is to somehow pass the argument ( category
) to a completely different view. This can be done, for example, by modifying the javascript that triggers autocomplete. Meaning, you will need to change getQuery
( http://django-autocomplete-light.readthedocs.org/en/stable-2.xx/script.html#override-autocomplete-js-methods ) to add category=foo
to the url which is called and then, on choices_for_request
read self.request.GET
QueryDict
to get that value.
Another way to do this is to put a category parameter on your session and then read the session into choices_for_request
. For example, on __init__
your view you will do something like self.request.session['category'] = 'foo'
, and on choices_for_request
you will get this value.
source to share