我正在使用django-autocomplete-light和django_filters。我看了django-filter with django autocomplete-light,但我的自动完成功能无效。
Models.py:
class ProfessionalDevelopment(models.Model):
Name = models.CharField("Professional Development", max_length=20,default = "None")
ProfessionalExperience = models.ManyToManyField(Person, through='PersonToProfessionalDevelopment')
class PersonToProfessionalDevelopment(models.Model):
PersonID = models.ForeignKey(Person, on_delete=models.CASCADE)
ProfID = models.ForeignKey(ProfessionalDevelopment, on_delete=models.CASCADE)
Desc = models.CharField("Professional Development Description", max_length=30, default="None")
Views.py:
class ProfessionalDevelopmentAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = ProfessionalDevelopment.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
urls.py
urlpatterns = [url(r'^search/ProfessionalDevelopment-autocomplete/$', ProfessionalDevelopmentAutocomplete.as_view(),
name='ProfessionalDevelopment-autocomplete']
Filters.py:
ProfessionalDevelopment = django_filters.CharFilter(name='professionaldevelopment__Name', lookup_expr='icontains',
widget=autocomplete.ModelSelect2(url='RSR:ProfessionalDevelopment-autocomplete'))
我收到错误说' list'对象没有属性' queryset'。然后我将代码更改为autocomplete.Select2而不是autocomplete.ModelSelect2(根据https://github.com/yourlabs/django-autocomplete-light/issues/763)。虽然没有错误,但我无法输入文本输入框。有人能帮助我吗?感谢
答案 0 :(得分:2)
你想根据它的名字过滤模型ProfessionalDevelopment。 您需要在以下步骤中进行修改: 1,在ProfessionalDevelopment模型上完成str或unicode,否则过滤器上显示的选项将为id。
class ProfessionalDevelopment(models.Model):
Name = models.CharField("Professional Development",
max_length=20,default = "None")
ProfessionalExperience = models.ManyToManyField(Person,
through='PersonToProfessionalDevelopment')
def __unicode__(self):
return self.name
2,更改ProfessionalDevelopment的过滤字段:
ProfessionalDevelopment = django_filters.ModelChoiceField(
queryset=ProfessionalDevelopment.objects.all(),
widget=autocomplete.ModelSelect2(url="yourcompleteurl")
)
这些步骤可以解决您的问题。
并且不要忘记在模板中添加{{form.media}}