【问题标题】:django-autocomplete-light error = 'list' object has no attribute 'queryset'django-autocomplete-light 错误 = 'list' 对象没有属性 'queryset'
【发布时间】:2023-03-11 22:39:01
【问题描述】:

我是 django 的新手,我需要你的帮助,在设置我的测试之后,我尝试了很多天来理解 django-autocomplete-light, http://192.168.0.108:8000/country-autocomplete/ 工作,数据显示如下http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#overview

但是在执行下一步之后,我收到错误:

AttributeError at /auto
'list' object has no attribute 'queryset'
Request Method: GET
Request URL:    http://192.168.0.108:8000/auto
Django Version: 1.10.3
Exception Type: AttributeError
Exception Value:'list' object has no attribute 'queryset'
Exception Location: /home/alcall/ENV/lib/python3.4/site-packages/dal/widgets.py in filter_choices_to_render, line 161

在我的设置下:

网址:

from dal import autocomplete
from django.conf.urls import url
from django.contrib import admin
from rates.view.index import *
from rates.view.index import UpdateView

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(
    r'^country-autocomplete/$',
    CountryAutocomplete.as_view(),
    name='country-autocomplete',
),
url(r'^auto$',
    UpdateView.as_view(),
    name='select',
),
]

models.py

from __future__ import unicode_literals
from django.db import models

class Country(models.Model):
    enabled = models.IntegerField()
    code3l = models.CharField(unique=True, max_length=3)
    code2l = models.CharField(unique=True, max_length=2)
    name = models.CharField(unique=True, max_length=64)
    name_official = models.CharField(max_length=128, blank=True, null=True)
    prix = models.FloatField()
    flag_32 = models.CharField(max_length=255, blank=True, null=True)
    flag_128 = models.CharField(max_length=255, blank=True, null=True)
    latitude = models.DecimalField(max_digits=10, decimal_places=8,     blank=True,$
    longitude = models.DecimalField(max_digits=11, decimal_places=8, blank=True$
    zoom = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'country'

    def __str__(self):
        return self.name

查看(也包括表单)

from dal import autocomplete
from django.shortcuts import render
from rates.models import Country
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django import forms
from django.core.urlresolvers import reverse_lazy
from django.views import generic

class CountryAutocomplete(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 Country.objects.none()

        qs = Country.objects.all()

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

        return qs

class Form_country(forms.ModelForm):
    class Meta:
       model = Country
       fields = ('name', 'code2l')
       widgets = {
          'name': autocomplete.ModelSelect2Multiple(
            'country-autocomplete'
           )
       }

class UpdateView(generic.UpdateView):
    model = Country
    form_class = Form_country
    template_name = 'fr/public/monformulaire.html'
    success_url = reverse_lazy('select')


    def get_object(self):
        return Country.objects.first() 

【问题讨论】:

  • 请验证您共享的代码。它看起来不正确。 - 例如,url 模式以 autos 为目标,但您的 url 只是 auto
  • 我把它从 r'^autos?$ 改成 r'^auto$',还是一样的问题
  • 请发布完整的回溯

标签: python django django-autocomplete-light


【解决方案1】:

我有同样的问题。这里的问题在于小部件。试图修复它很长时间。对我有用的唯一方法是更改​​表单的小部件。

如果没关系,您可以改用autocomplete.ListSelect2,它对我有用。

所以试试这个:

class Form_country(forms.ModelForm):
    class Meta:
       model = Country
       fields = ('name', 'code2l')
       widgets = {
          'name': autocomplete.ListSelect2(
            'country-autocomplete'
           )
       }

实际上,您可以尝试任何其他自动完成小部件并查看它的工作情况

【讨论】:

    【解决方案2】:

    如果您在 __init__() 中创建小部件,那么 issue #790 的解决方法会有所帮助:

    form.fields['name'].widget.choices = form.fields['name'].choices
    

    【讨论】:

      【解决方案3】:

      这是我的实现,我用它来建议模型中已经存在的相似名称

      重要提示:您必须完成所有这些操作后,别忘了运行python manage.py collectstatic 另请注意,您希望在表单字段中包含placeholder,您必须在小部件autocomplete 小部件中使用data-placeholder

      当你运行它时,你会看到这条消息

      找到另一个具有目标路径的文件 '管理员/js/jquery.init.js'。它将被忽略,因为只有第一个 遇到的文件被收集。如果这不是您想要的,请确保 每个静态文件都有唯一的路径。

      这就是文档声明 here 必须在 INSTALLED_APPS 中将 daldal_select2 放在 django.contrib.admin 之前的原因

      models.py

      from django.db import models
      
      class Patient(models.Model):
          name = models.CharField(max_length=100)
          stable = models.BooleanField(default=False)
      

      views.py

      from django.db.models import Q
      from dal import autocomplete
      
      class NewName(autocomplete.Select2QuerySetView):
          """Suggest similar names in form"""
          def get_queryset(self):
              qs = People.objects.filter(stable=True)
              if self.q:
                  query = Q(name__contains=self.q.title()) | Q(name__contains=self.q.lower()) | Q(name__contains=self.q.upper())
                  qs = qs.filter(query)
              return qs
      

      urls.py

      from django.urls import path
      from . import views
      urlpatterns = [
          path('new-name/', views.NewName.as_view(), name='new_name_autocomplete'),
      ]
      

      forms.py

      class PatientForm(forms.ModelForm):
          class Meta:
              model = Patient
              fields = ["stable", "name"]
      
              widgets = {
                  "name" : autocomplete.ModelSelect2(url=reverse_lazy('new_name_autocomplete'), attrs={'class' : 'form-control', 'data-placeholder' : "Name"}),
      

      我不得不修改dal/widgets.py 并注释掉查询集过滤,如下所示。这似乎是一个错误或什么的。该问题已被提出here。但是如果你使用 autocomplete.ListSelect2() 作为你的小部件,那么就不需要了。

      class QuerySetSelectMixin(WidgetMixin):
          """QuerySet support for choices."""
      
          def filter_choices_to_render(self, selected_choices):
              """Filter out un-selected choices if choices is a QuerySet."""
              # self.choices.queryset = self.choices.queryset.filter(
              #     pk__in=[c for c in selected_choices if c]
              # )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-31
        • 1970-01-01
        • 2020-10-06
        • 2021-08-05
        • 2017-06-22
        • 2013-05-10
        • 1970-01-01
        • 2021-05-08
        相关资源
        最近更新 更多