django-tables2:显示字典

问题描述

我想显示不是来自模型的字典列表。该列表是通过调用外部API(GETAPIINFO()生成的。该字典看起来像这样:

[{"name": "testname","value": 23},{"name": "test2name": "value": 123}]

我的views.py看起来像这样:

class Index(SingleTableView):
    table_class = ProductTable
    login_url = '/login/'

    def get_table_data(self):
         return(GETAPIINFO())

任何tables.py: 将django-tables2导入为表格

class ProductTable(tables.Table):
    PName= tables.columns.TemplateColumn(template_code=u"""{{ record.name}}""",orderable=False,verbose_name='productName')

    class Meta:
        attrs = {"class": "table table-striped table-hover table-borderless",}
        fields = ("PName",)
        sequence = fields   

我的模板:

{% extends 'base.html' %}
{% load render_table from django_tables2 %}

{% block content %}
    {% render_table table %}
{% endblock content %}

这会导致错误

... lib \ site-packages \ django_tables2 \ templatetags \ django_tables2.py“,渲染中的第145行 引发ValueError(“期望的表或查询集,而不是{}”。format(klass))

ValueError:预期的表或查询集,而不是列表

解决方法

我已经有一段时间没有使用它了,但是根据django-tables2文档,数据输入应该接受一个列表。

 class Index(SingleTableView):
    table_class = ProductTable
    login_url = '/login/'

    def get_table_data(self):
        """
        Return the table data that should be used to populate the rows.
        """
        return GETDATAFROMAPI()

您的ValueError发生在哪里?