Login

render_to_json

Author:
marinho
Posted:
November 16, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Explanation:

I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.

Setup:

Saves the snippet as myproject/utils.py or add the code to some place in your project with same ends.

Use in a view:

from myproject.utils import render_to_json

from django.contrib.admin.models import User

def json_view(request):
    admin_user = User.objects.get(username='admin')

    return render_to_json(
        'json/example.json',
        locals(),
    )

Update:

This code can be used as complement to http://www.djangosnippets.org/snippets/154/ too.

1
2
3
4
5
6
7
8
9
frm django.shortcuts import render_to_response

def render_to_json(*args, **kwargs):
    response = render_to_response(*args, **kwargs)
    response['mimetype'] = "text/javascript"
    response['Pragma'] = "no cache"
    response['Cache-Control'] = "no-cache, must-revalidate"

    return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

kcarnold (on February 28, 2008):

JSON doesn't necessarily mean no cache. Don't blindly copy-paste; think about if your data can be cached.

#

Please login first before commenting.