将django cms页面渲染为json

时间:2015-11-13 06:39:53

标签: python json django django-cms

我有一个django CMS页面,我希望将渲染的html制作成json对象(将CMS html转储为JSON),这可能吗?我希望它看起来像这样:

enter image description here

我该怎么做?

经过一番挖掘,这就是我所管理的。

CMS有一个views.py,它有一个功能“details(request,slug)” 我使用这个方法来渲染所需的页面,通过传递我需要渲染的页面的slug,获得响应并将其放入JSON对象并返回。

from cms.views import details

 def index(request, topic):

if topic == 'home':
    template = details(request, '')
else:
    template = details(request, topic)

content = ''
if hasattr(template, 'render'):
    # TemplateResponse must call render() before we can get the content
    content = template.render().content
else:
    # HttpResponse does not have a render() method
    content = template.content

# Send JSON response
return JsonResponse({ 
    'createdAt': datetime.datetime.now(),
    'content': content 
})

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我认为这应该相当容易。而不是从模板返回渲染的输出,将其放在字典中。然后根据您的目的,from json import dumpsdumpdump(dictionary) / dumps(dictionary)dumps为您提供了一个字符串。 dump为您提供更高级的东西。