我使用的是自动完成灯,由于某种原因,这个特定的课程无效 - 我无法看到它与工作自动完成之间的任何重大差异。我的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)
答案 0 :(得分:1)
这是因为您从AutocompleteBase而不是AutocompleteModelBase继承!您也可以使用AutocompleteModelTemplate。
查看如何在v2的文档中解释自动完成设计(该部分不会从v1更改为v2):http://django-autocomplete-light.readthedocs.org/en/v2/autocomplete.html