2

我正在使用 autocomplete-light,由于某种原因,这个特定的类无法正常工作——我看不出它与正常工作的自动完成之间有任何重大区别。我的 VirtualHost 包含一个到主机的 fk,前提是Host.contain_virtuals=True

这是我的表格:

class VirtualHostForm(ServerForm):
    def __init__(self, *args, **kwargs):
        super(VirtualHostForm, self).__init__(*args, **kwargs)

        self.helper.form_id = 'virtual_host_form'

    host = forms.ModelChoiceField(Host.objects.all(),
        widget=autocomplete_light.ChoiceWidget('HostAutocomplete'), 
        label='Associated Host'
    class Meta:
        model = Virtual
        fields = ServerForm.Meta.fields + ['host',]
        widgets = autocomplete_light.get_widgets_dict(Server)

我尝试了两种方法,每种方法都有自己的错误:

class HostAutocomplete(autocomplete_light.AutocompleteBase):
    #registers autocomplete for hosts that can contain virtuals
    autocomplete_js_attributes = {'placeholder': 'Select a host'}
    widget_template='assets/subtemplates/autocomplete_remove.html',
    choice_template='assets/_autocomplete_choice.html',

    def choices_for_request(self):
        q = self.request.GET.get('q', '')
        hosts = Host.objects.values_list('name', flat=True)
        return hosts.filter(name__icontains=q, contain_virtuals=True).distinct()


autocomplete_light.register(HostAutocomplete)

这样,我得到错误:'NotImplementedType' object is not callable. 这似乎与没有choices_for_values方法有关(尽管我的其他一些自动完成功能没有)所以我补充说:

def choices_for_values(self):
    choices = Host.objects.filter(id__in=self.values)
    return choices

(我真的不知道我在这里做什么——我在文档中找不到太多,所以我做了我最好的猜测)。

这给了我一个invalid literal for int() with base 10:我猜这意味着它正在查看名称,而不是 pk 用于外键关系?这是一个猜测。

应该注意的是,上述所有尝试都没有正确呈现模板格式,但至少提供了正确的选项选项。

所以最后我尝试了:

autocomplete_light.register(
    Host,
    autocomplete_light.AutocompleteModelTemplate,
    name='HostAutocomplete',
    widget_template='assets/subtemplates/autocomplete_remove.html',
    choice_template='assets/_autocomplete_choice.html',
    autocomplete_js_attributes={'placeholder': 'Type associated host'},
    search_fields=['name'],
    )

它保存(并包含正确的格式)但不过滤基于contain_virtuals=True; 它只包括所有可能的主机。

编辑:

感谢@jpic在下面的帮助,这有效:

class HostAutocomplete(autocomplete_light.AutocompleteModelTemplate):
    #registers autocomplete for hosts that can contain virtuals
    autocomplete_js_attributes = {'placeholder': 'Select a host'}
    choice_template='assets/_autocomplete_choice.html',

    def choices_for_request(self):
        q = self.request.GET.get('q', '')
        hosts = Host.objects.filter(contain_virtuals=True,name__icontains=q).distinct()
        return hosts

    def choices_for_values(self):
        choices = Host.objects.filter(id__in=self.values)
        return choices

autocomplete_light.register(Host, HostAutocomplete)
4

1 回答 1

2

这是因为您继承自 AutocompleteBase 而不是 AutocompleteModelBase !您也可以使用 AutocompleteModelTemplate。

查看 v2 文档中如何解释自动完成设计(该部分不会从 v1 更改为 v2):http ://django-autocomplete-light.readthedocs.org/en/v2/autocomplete.html

于 2014-03-19T18:41:04.467 回答