【问题标题】:Error Using django-tables2 - Expected table or queryset, not 'str'使用 django-tables2 时出错 - 预期的表或查询集,而不是“str”
【发布时间】:2015-06-23 08:46:27
【问题描述】:

我正在尝试使用 django-tables2 为我的应用程序创建一些表,但遇到了一些困难。我正在使用 Python 2.7 和 Django 1.7。我正在按照教程进行操作,但遇到了问题。

我需要创建一个 Table 类进行自定义。但是,每当我这样做时,都会收到以下错误:

预期的表或查询集,而不是“str”。

在完成someresearch 之后,看起来我使用的是旧版本的 django-tables2。但是,我昨天刚刚使用pip install django-tables2 安装了它,并在半小时前更新了它。知道如何让 django-tables2 正常工作吗?

编辑 - 问题已解决。我使用的是{% render_table people %} 而不是{% render_table table %}

【问题讨论】:

    标签: python-2.7 django-1.7 django-tables2


    【解决方案1】:

    我也遇到过这个问题。您应该做的第一件事是检查您的更新:

    sudo pip install django-tables2 --upgrade
    sudo pip install django-tables2-reports --upgrade
    

    升级也没有解决我的问题。
    如果您已经升级了这些版本。你应该检查你的实现。如果您使用的是基于类的视图,并且您可能实现了视图、模板、表格。您可能忘记了网址:

    /* I give the example with respect to other post*/
    urls.py  /*Same dic with table.py,models..etc*/
    
    from .views import SomeTableView   
    urlpatterns = patterns('',
                       url(r"^$", SomeTableView.as_view(), name="index"),
    
                       
                       )
    

    如果它不是您网站的索引,您可能需要更改 r"^$"name="index"

    【讨论】:

      【解决方案2】:

      根据django-tables2 documentation:
      tutorial/views.py中,类名是PersonListView here

      我将班级名称从 PersonListView 更改为 PersonTableView 并在 urls.py 中进行了此更改。

      这样做解决了我的问题。

      为什么会出现这个问题? 请任何人告诉我。

      【讨论】:

        【解决方案3】:

        遇到了同样的问题。我忘了在视图类的参数中添加SingleTableMixin

        【讨论】:

        • Sharpless512 所说的类似,但就我而言,我忘记将我的观点从ListView 更新为SingleTableView
        • 这真的很有帮助:)
        【解决方案4】:

        我认为你的问题不在于 django-tables2 的版本。在这里,我认为当您将变量从视图传递到模板时,您传递的是字符串而不是查询集/表类对象。对于工作示例:

        表类:

        class SomeTable(tables.Table):
        
            class Meta:
                model= SomeModel
                attrs = {"class": "paleblue"}
        

        查看类:

        class SomeTableView(SingleTableView):
            model = SomeModel
            template_name = 'test.html'
            table_class = SomeTable
        

        模板:

         {% load render_table from django_tables2 %}
         {% render_table table %}   <!-- Here I am passing table class -->
        

        或者你可以直接发送一个查询集来渲染表格:

        class SomeView(TemplateView):
             def get(self, request, *args, **kwargs):
                 data = SomeModel.objects.all()
                 context = self.get_context_data(**kwargs)
                 context['table'] = data
                 return self.render_to_response(context)
        

        并像这样渲染它:

        {% load render_table from django_tables2 %}
        {% render_table table %} <!-- Here I am passing queryset -->
        

        【讨论】:

        • 这是最好的答案。
        猜你喜欢
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2021-04-24
        • 2021-12-19
        • 2023-04-10
        • 1970-01-01
        相关资源
        最近更新 更多