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
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
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.