Login

render_to_json

Author:
marinho
Posted:
November 16, 2007
Language:
Python
Version:
.96
Tags:
template json
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. CSV to JSON Fixture by briangershon 5 years, 11 months ago
  2. Breaking tests.py into multiple files by gsakkis 5 years, 3 months ago
  3. Format transition middleware by limodou 8 years, 5 months ago
  4. Custom model field to store dict object in database by rudyryk 5 years, 3 months ago
  5. JSONField by deadwisdom 7 years, 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.