How do I return JSON without using a template in Django?

前端 未结 9 1609
再見小時候
再見小時候 2020-12-04 07:01

This is related to this question: Django return json and html depending on client python


I have a command line Python API for a Django app. When I access the a

9条回答
  •  被撕碎了的回忆
    2020-12-04 07:38

    If you want to pass the result as a rendered template you have to load and render a template, pass the result of rendering it to the json.This could look like that:

    from django.template import loader, RequestContext
    
    #render the template
    t=loader.get_template('sample/sample.html')
    context=RequestContext()
    html=t.render(context)
    
    #create the json
    result={'html_result':html)
    json = simplejson.dumps(result)
    
    return HttpResponse(json)
    

    That way you can pass a rendered template as json to your client. This can be useful if you want to completely replace ie. a containing lots of different elements.

提交回复
热议问题