Django Autocomplete Light-“无法加载结果”

时间:2019-08-04 10:52:17

标签: django autocomplete django-views django-autocomplete-light

我在一个小型应用程序上使用Django-autocomplete-light。用户界面似乎正常工作,我可以从一些可见的值中进行选择。当我在框中键入一个或多个字母时,就会出现问题。通常,它应该过滤/选择结果,相反,我会收到错误消息“无法加载结果”(参见图片)。

似乎jquery工作正常,除了我在框中键入内容时不进行过滤。很高兴添加更多代码,只是不确定我需要添加什么。

models.py

class Encounter(models.Model):
    patid = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name=('Patient Name'), related_name='patient')
    created_by = models.ForeignKey(Users, editable=False, null=True, blank=True, on_delete=models.PROTECT, related_name='encounter_created_by')
    encounter_date = models.DateField()
    encounter_label = models.ForeignKey(EncounterReason, on_delete=models.PROTECT, verbose_name=('Encounter Reason'), related_name='fk_reason')

class EncounterReason(models.Model):
    reason = models.CharField(max_length=256, blank=True, null=True)
    valueset_id = models.CharField(max_length=256, blank=True, null=True)

views.py

class EncounterReasonAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated:
            return EncounterReason.objects.none()
        qs = EncounterReason.objects.all()
        if self.q:
            qs = qs.filter(name__istartswith=self.q)
        return qs

forms.py

class EncounterForm(forms.ModelForm):
    encounter_date = forms.DateField(initial=datetime.date.today, widget = DateInput())
    encounter_notes = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Encounter Notes', 'id': 'editor', 'rows':50, 'cols':25}))
    encounter_label = forms.ModelChoiceField(queryset=EncounterReason.objects.all(),
        widget=autocomplete.ModelSelect2(url='encounterreason-autocomplete')
    )

    class Meta:
        model = Encounter
        fields = ('__all__')

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('clinicalviewer.urls')),
    path('encounterreason-autocomplete/', views.EncounterReasonAutocomplete.as_view(),
         name='encounterreason-autocomplete'),
]

无需在框中输入任何内容: enter image description here

现在,当我在框中输入内容时(有些对象以“ r”开头): enter image description here

错误: 在控制台中,出现以下错误: jquery.js:9203 GET http://127.0.0.1:8000/encounterreason-autocomplete/?q=r 500(内部服务器错误)

1 个答案:

答案 0 :(得分:2)

EncounterReason没有字段name,因此以下过滤器将错误

if self.q:
    qs = qs.filter(name__istartswith=self.q)

您可能希望过滤reason字段

if self.q:
    qs = qs.filter(reason__icontains=self.q)