autocomplete_light未使用choice_for_request显示正确的建议

时间:2014-12-18 19:43:42

标签: django django-models django-forms django-autocomplete-light

我在django autocomplete-light中有modal form。我想在建议框中应用动态过滤,这就是我在choice_for_request()中使用autocompletebasemodel的原因。但由于使用choice_for_request(),建议为not according to the keyword typed,但可以输入所有值。

这是我的表格:

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)

这是注册表和类:

autocomplete_light.register(Items, AutoComplete )

类:

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]  

我真的不知道在changes_for_request中要做出哪些更改才能使其正常工作

1 个答案:

答案 0 :(得分:0)

在浏览了各种文档之后,正确处理的解决方案是

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]  

我错过了

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

autocomplete-light使用get方法和预定义文字q来传输由user键入的值。 我无法理解q的含义。经过一些点击和试用,我得到它用于在建议框中存储用户给定的值。