Serves serialized QuerySet or other list passed in data parameter as json content.
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 30 31 32 33 34 35 36 37 38 | from django.core.serializers.json import DjangoJSONEncoder
import simplejson as json
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.core import serializers
class JsonResponse(HttpResponse):
error = ""
__data = []
def __set_data(self, data):
self.__data = (isinstance(data, QuerySet) or hasattr(data[0], '_meta'))\
and serializers.serialize('python', data) or data
data = property(fset = __set_data)
def __get_container(self):
return json.dumps(
{
"data": self.__data,
"error":self.error,
}, cls = DjangoJSONEncoder)
def __set_container(self, val):
pass
_container = property(__get_container, __set_container)
def __init__(self, *args, **kwargs):
kwargs["mimetype"] = "application/javascript"
if "data" in kwargs:
self.data = kwargs.pop("data")
if "error" in kwargs:
self.error = kwargs.pop("error")
super(JsonResponse, self).__init__(*args, **kwargs)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.