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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 months ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 5 months ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 1 week 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.