【问题标题】:django-tables2: Displaying a dictdjango-tables2:显示字典
【发布时间】:2021-02-16 13:02:41
【问题描述】:

我想显示不是来自模型的字典列表。该列表是通过调用外部 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 行,在渲染中 raise ValueError("预期的表或查询集,不是 {}".format(klass))

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

【问题讨论】:

  • SingleTableView 有一个 get_table_data 方法。您可以在视图中覆盖该方法并返回 API 数据
  • 可以添加导入吗?专门用于 ProductTable
  • 你的模板里有什么?
  • 我无法从这里找出问题所在。抱歉,我无法提供更多帮助。我会努力找出传递给模板标签的对象。
  • 您看到的 ValueError 是因为 template 中的 table 变量是一个列表而不是一个 Table,这里:{% render_table table %}。它与您检索数据的方式没有任何关系。我注意到的一件事是您的 GETAPIINFO 示例数据写入不正确,您有一个“:”,您应该有一个“,”。

标签: django django-tables2


【解决方案1】:

我已经有一段时间没有使用它了,但是根据 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 发生在哪里?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多