user3441273
user3441273

Reputation: 45

Displaying JSON data

In django my view.py is

import json      
from django.http import HttpResponse
from django.template import Template, Context
from django.shortcuts import render_to_response

def ajax(request):
    obj =[dict(a = 1,b = 2)]
    jsons=json.dumps(obj)
    print jsons 
    return render_to_response("2.html", {"obj_as_json": jsons})

I want to display value of a and b that are JSON in my template 2.html. Please help me to write the code.

Upvotes: 0

Views: 301

Answers (1)

Sahil kalra
Sahil kalra

Reputation: 9034

I don't understand the usage of View.

Why do you want to pass JSON object as a context value while Template Rendering ?

The standard is When you do a Ajax request its response should be a JSON response i.e mimetype=application/json.

So, You should render the template normally and Convert the result into JSON and return. e.g:

def ajax(request):
    obj = {
       'response': render_to_string("2.html", {"a": 1, "b": 2})
    }
    return HttpResponse(json.dumps(obj), mimetype='application/json')

OR

you can create a JSONResponse class Similar to HttpResponse to make it generic . e.g.

class JSONResponse(HttpResponse):
    """
        JSON response
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type=None):
        super(JSONResponse, self).__init__(
            content=json.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type,
        )

and use like : return JSONResponse(obj)

This has been added by default in django 1.7: https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects

Upvotes: 1

Related Questions