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

Harshil Parikh picture Harshil Parikh · Jan 29, 2012 · Viewed 31.4k times · Source

In my view function, I'd like to return a json object (data1) and some text/html (form). Is this possible?

Here is part of my views.py:

if request.is_ajax() and request.method == 'POST':
...
    if form.is_valid():
        answer = form.cleaned_data['answer'] # Answer extracted from form is also a string
        a1 = ques1.correct_answer
                    if a1 == answer:
            test1 = question_list.get(id=nextid)
            form = AnswerForm(test1)
            ques1 = question_list.filter(id=nextid)                     # Filter next question as <qs>
            data1 = serializers.serialize("json",ques1)                 # Json-ize
    # ********EDITED HERE **********        
            variables1 = Context({
                'form' : form,
                'q1'   : data1,
            })  
            #response = HttpResponse()
            #response['data1'] = response.write(data1)
            #response['form'] = response.write(form) 
            if nextid <= qsnlen:
                return HttpResponse(variables1, mimetype="application/json")
                #return HttpResponse(response)
            else:
...

I'd like to send back both the form html and the ques1 json object. How can I do this? Thanks in advance.

Answer

AdamKG picture AdamKG · Jan 29, 2012

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