Login

universal JSONResponse

Author:
guetux
Posted:
April 12, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Repsonse with JSON in any case, either if it's a model, queryset or whatever

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.db.models import Model
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.utils.encoding import force_unicode
from django.utils.simplejson import dumps, JSONEncoder

def jsonify_model(model):
    model_dict = model.__dict__
    for key, value in model_dict.items():
        if key.startswith('_'):
            del model_dict[key]
        else:
            model_dict[key] = force_unicode(value)
    return model_dict

class API_JSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, QuerySet):
            return [jsonify_model(o) for o in obj]
        if isinstance(obj, Model):
            return jsonify_model(obj)
        return JSONEncoder.default(self,obj)

class JSONResponse(HttpResponse):
    status_code = 200

    def __init__(self, data):
        json_response = dumps(data, ensure_ascii=False, indent=2, cls=API_JSONEncoder)
        HttpResponse.__init__(self, json_response, mimetype="text/javascript")

More like this

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

Comments

Please login first before commenting.