Django 自动完成灯 - "The results could not be loaded"

Django Autocomplete Light - "The results could not be loaded"

我在一个小型应用程序上使用 Django-autocomplete-light。 UI 似乎有效,我可以从一些可见值中 select 。当我在框中键入一个或多个字母时出现问题。通常它应该 filter/select 结果,相反,我得到错误 "The results could not be loaded" (见图)。

似乎 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'),
]

不在框中输入任何内容:

现在,当我在框中输入内容时(有些对象以 "r" 开头):

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

EncounterReason 没有字段 name 所以下面的过滤器会出错

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

您可能想要过滤 reason 字段

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