我正在尝试构建数据过滤分页页面。这是我的过滤器
from shop.models import CC
import django_filters
name_values = [("", "---------")] + list(CC.objects.values_list('name', 'name').distinct())
city_values = [("", "---------")] + list(CC.objects.values_list('city', 'city').distinct())
class CCFilter(django_filters.FilterSet):
name = django_filters.ChoiceFilter(choices=name_values)
city = django_filters.ChoiceFilter(choices=city_values)
class Meta:
model = CC
fields = {
'name': ['exact'],
'city': ['exact'],
}
查看:
@method_decorator(login_required, name='dispatch')
class BuyView(ListView):
paginate_by = '25'
queryset = CC.objects.all()
context_object_name = "ccs"
template_name = "buy.html"
def get_queryset(self):
queryset = super(BuyView, self).get_queryset()
queryset = CCFilter(self.request.GET, queryset)
return queryset
def get_context_data(self, **kwargs):
context = super(BuyView, self).get_context_data(**kwargs)
context['cart'] = Cart.objects.get(user=self.request.user)
return context
def get_paginate_by(self, queryset):
"""
Paginate by specified value in querystring, or use default class property value.
"""
return self.request.GET.get('per_page', self.paginate_by)
型号:
class CC(models.Model):
number = models.CharField(max_length=19, unique=True)
name = models.CharField(max_length=70)
在documentation中写道,表单对象在模板中可用作上下文属性。但是当我{{ ccs.form|crispy }}
时,什么都没有出现。虽然我可以使用?name=christian
这样的get请求过滤数据,但效果很好。但是我如何访问表单?
答案 0 :(得分:1)
文档显示您可以编写视图并手动将过滤器传递给模板,也可以使用内置的FilterView
。您目前正在使用Django的ListView
,因此除非您明确地使用过滤器,否则不会将过滤器传递给模板。
您可以尝试更改视图以使用FilterView
。它看起来像这样。我遗漏了分页代码以保持简单。
from django_filters.views import FilterView
@method_decorator(login_required, name='dispatch')
class BuyView(FilterView):
filterset_class = CCFilter
template_name = "buy.html"
context_object_name = "ccs"
def get_queryset(self):
queryset = super(BuyView, self).get_queryset()
queryset = CCFilter(self.request.GET, queryset)
return queryset
def get_context_data(self, **kwargs):
context = super(BuyView, self).get_context_data(**kwargs)
context['cart'] = Cart.objects.get(user=self.request.user)
return context
在模板中,您可以使用{{ filter }}
访问过滤器,使用{{ filter.form }}