[Fixed]-Is it possible to return an HttpResponse in django with text & a json object?

13๐Ÿ‘

Use JsonResponse

from django.http import JsonResponse
response_data = {put your data into a dict}
return JsonResponse(response_data, status=201)
๐Ÿ‘คi_emmanuel

11๐Ÿ‘

Just put both pieces of data in a JSON container, one key with the form data and one with the HTML as a rendered string. In the browser, you can just pull both keys out & do your thing.

In your view:

form_json_data = get_form_json_data()
rendered_html = get_the_html()
return HttpResponse(json.dumps({
        "formdata": form_json, 
        "html": rendered_html}),
    content_type="application/json")

In js:

$.post(foo, postdata, function(data){
    var formdata = data.formdata
    var html = data.html;
    $(".html-target").replaceWith(html);
    do_whatever(formdata);
})
๐Ÿ‘คAdamKG

0๐Ÿ‘

To do this with one response; you need to send the JSON as a plain text in the context of your template response (HTML).

If you need to send JSON as as a separate JSON object, with its own mime type, then you need to write two views; one that sends back the JSON as application/json and the other that sends back the form (HTML).

EDIT:

You are not returning JSON objects, but you are turning a dictionary that has two items of two different types. As I explained in the comments, in one request/response cycle; you can only return one response which has a specific mime type that is based on the content and how you want the browser to handle it. Most of the time the content type is 'text/html'.

In your scenario, if you want to return both the HTML (which is your form), and the JSON response (which is a string), you need to return HTML.

If you want to return JSON to Jquery as a JSON object; you need to detect the request type. In your front end (the templates), you will initiate two requests โ€“ one from the browser, which will return back the form. The other from jQuery, which will return the appropriate JSON object.

Here is a possible approach to this:

  def foo(request):
     if request.is_ajax():
        ctx = dict()
        ctx['hello'] = 'world'
        return HttpResponse(json.dumps(ctx),content_type='application/json')
     else:
        return HttpResponse('hello world')
๐Ÿ‘คBurhan Khalid

Leave a comment