Universal JsonResponse

 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

  1. JsonResponse by zakj 6 years, 1 month ago
  2. universal JSONResponse by guetux 2 years, 1 month ago
  3. Format transition middleware by limodou 6 years, 2 months ago
  4. ajax_validator generic view by amitu 4 years, 7 months ago
  5. jsonify template filter by skam 6 years ago

Comments

(Forgotten your password?)