【发布时间】: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