【问题标题】:how to create a dependant drop down using autocomplete light如何使用自动完成灯创建依赖下拉菜单
【发布时间】:2014-12-17 14:58:08
【问题描述】:

我使用Django Model Formautocomplete_light 创建了一个表单。我想根据调用类时传递的论点过滤下拉列表item中的建议。

我的表格是

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)

我根据传递的category 的值在__init__ 中应用了过滤器,但它似乎不起作用。

注册表是

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

表格被称为

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

请建议我一种方法,以便我可以根据调用表单时传递的值优化搜索。

我已经尝试使用修改它

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]     

和注册表为 autocomplete_light.register(项目,自动完成) 通过这个,我知道category获取值none(因为我选择的默认值),这个方法似乎也不起作用。

有没有办法可以将category 的值传递给request_for_choices 以便细化搜索?

【问题讨论】:

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


    【解决方案1】:

    自动完成类的self.request.POST(或self.request.GETQueryDict不会包含比搜索查询更多的信息,因为它们在时传递视图已创建(因此self.request.POST.get('category', 'none') 将始终返回'none')。

    因此,困难的部分是以某种方式将参数 (category) 传递给完全不同的视图。这可以通过例如修改调用自动完成的 javascript 来完成。这意味着,您需要更改 getQuery (http://django-autocomplete-light.readthedocs.org/en/stable-2.x.x/script.html#override-autocomplete-js-methods) 以将 category=foo 附加到调用的 url,然后在 choices_for_request 读取 self.request.GET QueryDict 以获取该值。

    另一种方法是将类别参数放入会话中,然后在choices_for_request 中读取会话。例如,在视图的__init__ 上,您将执行self.request.session['category'] = 'foo' 之类的操作,而在choices_for_request 上,您将获得该值。

    【讨论】:

    • 我发现__init__ 无法使用自动完成功能。我尝试在__init__ 中打印something,但它不起作用。当我从类中删除自动完成模型时,something 得到打印,因此 init 工作。
    • 我的错。 init 正在工作。我在其他班级打印了这条消息。好吧,我在调用表单的地方使用了修改过的会话变量,然后在选择中检索。现在出现的问题是明确的choices_for_request 给出了所有过滤后的建议,而不是根据输入的文本..:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2021-07-11
    • 1970-01-01
    • 2018-04-27
    相关资源
    最近更新 更多