首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-autocomplete-light error = 'list‘对象没有属性'queryset’

django-autocomplete-light error = 'list‘对象没有属性'queryset’
EN

Stack Overflow用户
提问于 2016-11-27 03:39:17
回答 3查看 4.6K关注 0票数 3

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

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

代码语言:javascript
复制
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

下面是我的设置:

urls:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

视图(也包括表单)

代码语言:javascript
复制
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() 
EN

回答 3

Stack Overflow用户

发布于 2016-11-27 05:05:27

我也有同样的问题。这里的问题出在小部件上。我试着修了很长时间。对我来说,唯一有效的方法就是更改表单的小部件。

如果这无关紧要,你可以使用autocomplete.ListSelect2,它对我很有效。

所以试试这个:

代码语言:javascript
复制
class Form_country(forms.ModelForm):
    class Meta:
       model = Country
       fields = ('name', 'code2l')
       widgets = {
          'name': autocomplete.ListSelect2(
            'country-autocomplete'
           )
       }

实际上,您可以尝试任何其他自动完成窗口小部件,看看它是否工作

票数 6
EN

Stack Overflow用户

发布于 2017-03-06 23:35:23

如果您在__init__()中创建小部件,则此issue #790变通方法有助于:

代码语言:javascript
复制
form.fields['name'].widget.choices = form.fields['name'].choices
票数 2
EN

Stack Overflow用户

发布于 2018-06-05 18:50:25

下面是我的实现,我使用它来建议模型中已经存在的类似名称

重要提示:在您必须完成所有这些操作之后,不要忘记运行 python manage.py collectstatic**.**还请注意,您希望在表单域中包含一个placeholder,您必须在小部件autocomplete小部件中使用data-placeholder来执行此操作。

当您运行它时,您将看到以下消息

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

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

models.py

代码语言:javascript
复制
from django.db import models

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

views.py

代码语言:javascript
复制
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

代码语言:javascript
复制
from django.urls import path
from . import views
urlpatterns = [
    path('new-name/', views.NewName.as_view(), name='new_name_autocomplete'),
]

forms.py

代码语言:javascript
复制
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并注释掉查询集过滤,如下所示。这看起来像是个bug之类的。此问题已在here中提出。但是如果您使用autocomplete.ListSelect2()作为您的小部件,那么就没有必要这样做。

代码语言:javascript
复制
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]
        # )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40822373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档