【问题标题】:Python: Creating a list of dicts, where keys don't have quotes?Python:创建一个字典列表,其中键没有引号?
【发布时间】:2019-09-03 13:53:37
【问题描述】:

我正在使用 visjs 插件在我的页面上创建时间线。时间线代码要求我在一个列表中给它多个字典,如下所示:

  var items = new vis.DataSet([
     {id: 1, content: 'item 1', start: '2013-04-20'},
     {id: 2, content: 'item 2', start: '2013-04-14'},
     {id: 3, content: 'item 3', start: '2013-04-16', end: '2013-04-19'},
  ]);

现在我正在尝试通过使用 for 循环并将我的 dicts 添加到列表中来为我的索引视图创建类似的东西,然后我将其放入我的上下文中并在我的模板中使用它。我的代码如下所示:

class ItemIndex(SingleTableMixin, FilterView):
    model = Item
    context_object_name = 'items'
    template_name = 'accounting/item/item_index.html'

    def get_context_data(self, **kwargs):
        items = Item.objects.all()
        context = super().get_context_data(**kwargs)

        dict_list = []

        for item in items:
            dict = {
                "id": item.pk,
                "content": Item (# {item.pk})',
                "start": str(item.start), #DateField
                "end": str(item.end), #DateField
            }
            dict_list.append(dict)
        context.update({
            "dict_list": dict_list,
        })
        return context

现在我发现这不是最漂亮的解决方案,但我不知道更好的解决方案(也许有人有更好的主意)。

在我的 html 中,我像这样调用dict_list

var items = new vis.DataSet(
                "{{dict_list}}"
            );

我的问题是我要返回的列表如下所示:

[{'id': 3, 'content': 'Item (# 3)', 'start': '2020-01-01', 'end': '2020-01-03'}, {'id': 4, 'content': 'Item (# 4)', 'start': '2020-01-01', 'end': 'None'}]

我的问题是键周围的引号“破坏”了整个列表,因此我的时间线没有正确显示。

是否有一个很好的解决方案来以某种方式创建不带引号的键?

我正在使用 Python 3 和 Django 2.2。

感谢您的帮助!

【问题讨论】:

  • 您应该使用 Json 将 Python 数据转换为 JavaScript。
  • @WillemVanOnsem 我尝试这样做json.dumps(dict_list) 问题是:它保持不变,更糟糕的是:如果我尝试使用变音符号作为我的content 值(如“Ermäßigung”)我收到类似Erm\u00e4\u00dfigung (# 3)
  • 渲染时需要标记为安全,然后解析回来。

标签: python django dictionary


【解决方案1】:

您在这里有一个 Python 对象,通过使用{{ dict_list }},您可以获得该对象的str(..)HTML 转义 版本。您可能最好使用 JSON 作为中间格式。因此,您首先在上下文中对对象进行 JSON 编码:

context.update(
    dict_list=json.dumps(dict_list),
)

在模板端,您可以将 JSON 解析回来。您应该将 dict_list 变量标记为安全,以确保它不会对它进行 HTML 转义:

var items = new vis.DataSet(
    JSON.parse('{{ dict_list|safe }}')
);

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2020-07-29
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多