1
votes

I have a django CMS page, I want the rendered html to be made into a json object(dump the CMS html into JSON), is this possible? I'd like it to look something like this:

enter image description here

How would I go about this?

So after some digging , this is what I managed.

CMS has a views.py which has a function "details(request, slug)" I used this method to render the required page, by passing the slug of the page I need rendered , got the response and put it into a JSON object and returned this.

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 
})

Any better way of doing the same?

1
do you want to dump your HTML code into JSON? how do you imagine such output? - Nhor
link Something like this - at14

1 Answers

1
votes

I think this should be fairly easy. Instead of returning the rendered output from the template, put it in a dictionary. Then just from json import dumps or dump and dump(dictionary) / dumps(dictionary) depending on your purpose. dumps gives you a string. dump gives you something fancier.