Combine page content (html) and model instance (json) in ajax response

87 views
Skip to first unread message

Max Demars

unread,
Jun 12, 2014, 2:30:58 PM6/12/14
to django...@googlegroups.com
I would like my view to return the page content and some parameters that I would like to use in the Ext.Ajax.request success function.

views.py

    def importFile(request):
        form = ImportVectorForm()
        html_response = render_to_response("page_content.html", {'form': form, 'folder':folder, 'nodes':nodes},context_instance=RequestContext(request))
        if request.POST:
            form = ImportVectorForm(request.POST, request.FILES)
            if form.is_valid():
                ## here im dealing with the form...
                object = MyObject.objects.create()
                html_response = render_to_response("page_content.html", {'form': form},context_instance=RequestContext(request))
                json_param = serializers.serialize('json', object)
                return StreamingHttpResponse(html_response, content_type="plain/text")

            else:
                html_response = render_to_response("page_content.html", {'form': form},context_instance=RequestContext(request))

        return StreamingHttpResponse(html_response, content_type="plain/text")


ajax.js:

      importFileAjax = function(node_id){
        Ext.Ajax.request({
          method: "GET",
          form: "importForm",
          url: "/basqui/file/import/" + node_id + "/",
          success: function(r){
                      // here I would like to access the model instance created properties
                      Ext.get('table').update(r.responseText); //this update the page content
                   }
        });
      }

I would like to pass both html_response and json_param to Ajax. The fist to update a div and the second to access its properties.

What is the right way of doing that?

Max Demars

unread,
Jun 13, 2014, 8:50:22 AM6/13/14
to django...@googlegroups.com
I got the solution from Daniel Rossman on SO:

Firstly, use `render_to_string` to get the template fragment as an HTML string. Secondy, serialize your object as a Python dict, not JSON. Then you can convert the whole lot to JSON in one go.

    html = render_to_string("page_content.html", {'form': form}, context_instance=RequestContext(request))
    param = serializers.serialize('python', object)
    data = json.dumps({'html': html, 'param': param})
    return StreamingHttpResponse(data, content_type="application/json")

Now your JS can parse the JSON and access the `html` and `param` values.
Reply all
Reply to author
Forward
0 new messages