[英]Django filters dopdown menu valid choice error
i have a dataset with population by year and i need to it filter by year. 我有一个按年人口的数据集,我需要按年过滤。 it works with input value but it doesn't work with dropdown menu.
它适用于输入值,但不适用于下拉菜单。 it gives the error "Select a valid choice. That choice is not one of the available choices."
它给出错误“选择一个有效的选择。该选择不是可用的选择之一。”
models.py models.py
class Pyramid(models.Model):
year = models.IntegerField(default=0)
city = models.CharField(max_length=15)
men_population = models.IntegerField(default=0)
women_population = models.IntegerField(default=0)
filters.py filter.py
import django_filters
from .models import Pyramid
class YearFilter(django_filters.FilterSet):
year_f = django_filters.ModelChoiceFilter(queryset=Pyramid.objects.values_list('year',flat=True).distinct())
class Meta:
model = Pyramid
fields = ['year_f ']
views.py views.py
def Pyramid(request):
dataset = models.Pyramid.objects.all()
year_filter = YearFilter(request.GET, queryset=dataset)
context = {
'dataset': dataset,
'filter': year_filter,
}
return render(request, 'pyramid.html', context)
it shows me the year what i enter but gives error "Select a valid choice. That choice is not one of the available choices." 它向我显示了我输入的年份,但显示错误“选择一个有效的选择。该选择不是可用的选择之一。”
Thank you @dirkgroten i should define years from database firstly so i add code below and it works 谢谢@dirkgroten,我应该首先定义数据库的年份,所以我在下面添加代码,它可以正常工作
class YearChoiceFilter(django_filters.ChoiceFilter):
@property
def field(self):
self.extra['choices'] = [(a.Year, a.Year) for a in self.parent.queryset]
return super(YearChoiceFilter, self).field
class YearFilter(django_filters.FilterSet):
Year = YearChoiceFilter(field_name='Year')
class Meta:
model = Pyramid
fields = ['Year']
so now i wonder that can i add default year as 2018 for filter? 所以现在我想知道是否可以将默认年份添加为2018年作为过滤器?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.