Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

Django-filter: error: Enter a list of values when using the LinkWidget

Perhaps one of you could help me out with “Django-filter”. In my template an error shows up 'Enter a list of values’ when I want to use the LinkWidget. When I use the LinkWidget with django_filters.AllValuesMultipleFilter then in my template it shows the word "all" and the ID’s of te field categories

When I use it with the Django Form widget “widget=forms.CheckboxSelectMultiple)” then I’m able to filter the data.

What’s wrong with my code?
Thanks.
Krgds.

  # file: filters.py
from portfolio.models import Project,Category,Client
import django_filters
from django_filters.widgets import LinkWidget

from django import forms

# error: Enter a list of values.
class ProjectFilter(django_filters.FilterSet):
   categories = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(),# this a ManyToManyField 
       widget=django_filters.widgets.LinkWidget)

   class Meta:
           model = Project
           fields = ['categories' ]


# shows "all" and the ID’s of te field categories
class ProjectFilter(django_filters.FilterSet):
   categories = django_filters.AllValuesMultipleFilter(widget=django_filters.widgets.LinkWidget)  

   class Meta:
       model = Project
       fields = ['categories' ]
question from:https://stackoverflow.com/questions/66068475/django-filter-error-enter-a-list-of-values-when-using-the-linkwidget

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The LinkWidget will list the filtered results as an unordered list and list items in html. Ie:

<ul id="id_categories">
<li><a href="?categories=">All</a></li>
<li><a class="selected" href="?categories=1">Offices</a></li>
<li><a href="?categories=2"> Residential </a></li>
</ul>

To achieve this you can use “django_filters.filters.ModelChoiceFilter”. Despite that the field to be filtered is a ManyToManyField.

According to the documentation:

ModelMultipleChoiceFilter?

Similar to a MultipleChoiceFilter except it works with related models, used for ManyToManyFieldby default.

ModelChoiceFilter?

Similar to a ChoiceFilter except it works with related models, used for ForeignKey by default.

#filters.py
class ProjectFilter(django_filters.FilterSet):
    categories = django_filters.filters.ModelChoiceFilter(
        required=False,
        queryset=Category.objects.all(),
        widget=django_filters.widgets.LinkWidget
    )
    
    class Meta:
        model = Project
        fields = ['categories' ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...