django-autocomplete-light error = 'list' object has no attribute 'queryset'

后端 未结 3 1312
忘了有多久
忘了有多久 2021-01-03 10:29

i am new on django and i need your help, trying since many days to understand django-autocomplete-light, after setup my test, http://192.168.0.108:8000/country-autocomplete/

3条回答
  •  抹茶落季
    2021-01-03 10:39

    Here is my implementation, where I used it to suggest similar names that are already present in a model

    IMPORTANT: After you must have done all these, don't forget to run python manage.py collectstatic. Also note that you wish to include a placeholder in your form field you have to do it with data-placeholder in the widget autocomplete widget.

    When you run it, you'll see this message

    Found another file with the destination path 'admin/js/jquery.init.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.

    This is the reason the documentation states here that you must place dal and dal_select2 before django.contrib.admin in your INSTALLED_APPS

    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"}),
    

    I had to modify dal/widgets.py and comment out the queryset filtering as shown below. It seems to be a bug or something. The issue has been raised here. But if you're using autocomplete.ListSelect2() as your widget, then there's no need for that.

    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]
            # )
    

提交回复
热议问题