Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 427
Harshil Parikh Avatar asked Jan 29 '12 07:01

Harshil Parikh


People also ask

What is HttpResponse in Django?

HttpResponse (source code) provides an inbound HTTP request to a Django web application with a text response. This class is most frequently used as a return object from a Django view.

What is JSON response in Django?

JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.

What is QueryDict Django?

class QueryDict. In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.

What is request Meta in Django?

META contains all the metadata of the HTTP request that is coming to your Django server, it can contain the user agent, ip address, content type, and so on.


1 Answers

Use JsonResponse

from django.http import JsonResponse
response_data = {put your data into a dict}
return JsonResponse(response_data, status=201)
like image 193
i_emmanuel Avatar answered Oct 23 '22 19:10

i_emmanuel