使用django-tables2和django-filter在上下文中缺少过滤器集对象

时间:2018-10-20 15:24:13

标签: django django-filter django-tables2

我一直在尝试创建带有过滤器栏和用户表的视图。
我正在使用django-tables2django-filter库,并且有以下视图:

class UserListView(SingleTableView, FilterView):
    model = User
    template_name = 'admin/users.html'
    table_class = AdminUserTable
    filterset_class = UserFilter
    paginate_by = 10

但是问题是data-context中没有过滤集对象发送到模板,UserListView自身中也没有过滤集对象。
我试图将SingleTableView, FilterView替换为FilterView, SingleTableView,然后将上下文中filter键下的filterset对象传递给模板,但是在这种情况下,当我访问在url中没有过滤器参数的页面时它显示为空列表。但是,如果我在网址中放入?search=,则会显示所有用户,并且过滤效果很好。

2 个答案:

答案 0 :(得分:1)

我找到了解决方法:

def get_table_data(self):
    return self.filterset.qs

我不喜欢它,但是它可以工作。我相信有更好的解决方案。

答案 1 :(得分:0)

我遇到了同样的问题,并在文档中发现了“ strict”属性: https://django-filter.readthedocs.io/en/stable/ref/filterset.html#strict 但这仅对1.11版有效。

版本2的更改记录在: https://github.com/carltongibson/django-filter/pull/788

因此在视图中添加strict = False应该可以:

class UserListView(SingleTableView, FilterView):
    model = User
    template_name = 'admin/users.html'
    table_class = AdminUserTable
    filterset_class = UserFilter
    paginate_by = 10
    strict=False