Created
August 15, 2014 16:03
-
-
Save jackboot7/95cd58389ff9c385df5e to your computer and use it in GitHub Desktop.
Django JSON mixin for class based views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django import http | |
from django.core import serializers | |
from django.utils import simplejson as json | |
class JSONResponseMixin(object): | |
""" | |
Mixin to send a json response. It serialize the context variable into | |
a JSON object which can be sent to the browser or used as a service. | |
""" | |
def render_to_response(self, context): | |
"Returns a JSON response containing the context as the data." | |
return self.get_json_response(self.context_to_json(context)) | |
def get_json_response(self, content, **httpresponse_kwargs): | |
"Construct a HttpResponse object with the JSON data." | |
return http.HttpResponse(content, | |
content_type='application/json charset=utf8', | |
**httpresponse_kwargs) | |
def context_to_json(self, context): | |
"Convert the context dictionary into a JSON object" | |
self.create_field_dict(context) | |
#context = serializers.serialize("json", | |
#context["object_list"], | |
#ensure_ascii=False | |
#) | |
#return context | |
return json.dumps(context["fields"], indent=2, ensure_ascii=False) | |
def create_field_dict(self, context): | |
"Given a context, adds 'fields' list to be encoded." | |
fields = list() | |
for n in context['object_list']: | |
d = dict() | |
for f in n.get_field_names(): | |
d[f] = n.get_field_by_name(f).value_to_string(n) | |
fields.append(d) | |
context["fields"] = fields | |
return context |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an old piece of code that was hanging around my sandbox directory. I wrote this to use it with Django 1.3 IIRC.
Sure is deprecated by now.