如何在django-tables2中修复“参数数据到tableXXX是必需的”?

时间:2019-01-03 22:43:23

标签: django django-haystack django-tables2

我正在设置一个网上商店管理器,并且依靠django-tables2软件包来显示使用SimpleTableMixin的产品列表。我想向视图添加过滤器/搜索功能。根据django-tables2软件包的建议,可以依靠django-filter软件包提供过滤。但是,在具有许多字段的模型的情况下,几乎不可能有效地查询和开发那些表单。我的目标是使用django-haystack拥有一个输入搜索表单作为查询应该在相似表/表单中显示的模型实例的方式。

我试图将SimpleTableMixin添加到django-haystack包通用SearchView中。但是我继续收到以下错误:

TypeError at /manager/front/products/
Argument data to ProductTable is required

到目前为止,我的实现方式如下:

视图:

# ############## Products ############## (previous implementation with django-filter)
# @method_decorator(staff_member_required, name='dispatch')
# class ProductList(SingleTableMixin, FilterView):
#     model = Product
#     table_class = tables.ProductTable
#     filterset_class = filters.ProductFilter
#     template_name = 'manager/front/products/product_list.html'

############## Products ##############
@method_decorator(staff_member_required, name='dispatch')
class ProductList(SingleTableMixin, SearchView):
    model = Product
    table_class = tables.ProductTable
    template_name = 'manager/front/products/product_list.html'

表格:

import django_tables2 as tables
from front.models import Product

class ProductTable(tables.Table):
    class Meta:
        model = Product
        template_name = 'django_tables2/bootstrap.html'

search_indexes.py:

from haystack import indexes
from front.models import Product

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Product

网址:

path('front/products',views.ProductList.as_view(),name="manage_products"),    

模板:

{% extends 'base_site.html' %}
{% load render_table from django_tables2 %}
{% block content_title %}Manage Products{% endblock%}
{% block content %}
<form action="" method="get" class="form form-inline">
    {{ form }}
    <button class="btn btn-default" type="submit">Search</button>
</form>
{% render_table table %}
{% endblock %}

如何删除该错误并为列表视图提供有效的搜索功能?

1 个答案:

答案 0 :(得分:1)

确定要使用haystack.generic_views.SearchView而不是 haystack.views.SearchView吗?请注意,在https://django-haystack.readthedocs.io/en/latest/views_and_forms.html上显示为:

  

从2.4版开始,不建议使用haystack.views.SearchView中的视图,而推荐使用haystack.generic_views.SearchView中的新通用视图,该视图使用标准的基于Django类的视图,这些视图在受支持的每个Django版本中均可用通过Haystack。

因此,如果您使用的是haystack.views.SearchView,那么将永远不会调用get_context_data中的SingleTableMixin,因此不会在您的上下文中放置任何table(即{{1} }将为空)。实际上是因为我不喜欢table的参数为空时的行为(它的行为不同于其他Django标签/过滤器,即它抛出异常,而Django的标签/过滤器则无声地忽略了它),我通常将其放在一些{{1 }}检查。

更新

似乎无论出于何种原因,数据都不会传递到表中。我不确定为什么,现在无法进行测试,但是通过快速查看实现应该可以正常工作的源代码(考虑到SearchView具有{% render_table %}和{{ 1}}使用{% if table %}检索其数据)。无论如何,您都尝试覆盖get_queryset的某些方法以确保正确返回了表(请在此处查看TableMixin:https://django-tables2.readthedocs.io/en/latest/_modules/django_tables2/views.html)。

我认为最确定的解决方案是硬着头皮自己超越TableMixin。因此,请尝试将此类内容添加到您的课程中:

get_queryset

在我脑海中浮现出一个想法。由于配置错误或其他原因,TableMixin的{​​{1}}方法是否可能返回get_table

相关问题