@@ -0,0 +1,1704 @@
+import json%0Afrom django.http import HttpResponse, HttpRequest%0A%0A%0Aclass AsyncHandlerError(Exception):%0A    pass%0A%0A%0Aclass BaseAsyncHandler(object):%0A    %22%22%22%0A    Handles serving async responses for an ajax post request, say in a form.%0A    Usage:%0A    1) specify an allowed action slug in allowed actions%0A    2) implement the property %3Callowed action slug%3E_response, which returns a dict.%0A    example:%0A%0A    allowed_actions = %5B%0A        'create'%0A    %5D%0A    then implement%0A%0A    @property%0A    def create_response(self):%0A        return %7B%7D%0A%0A    %22%22%22%0A    slug = None%0A    allowed_actions = %5B%5D%0A%0A    def __init__(self, request):%0A        if not isinstance(request, HttpRequest):%0A            raise ValueError(%22request must be an HttpRequest.%22)%0A        self.data = request.POST if request.method == 'POST' else request.GET%0A        self.action = self.data.get('action')%0A%0A    def _fmt_error(self, error):%0A        return json.dumps(%7B%0A            'success': False,%0A            'error': error.message,%0A        %7D)%0A%0A    def _fmt_success(self, data):%0A        return json.dumps(%7B%0A            'success': True,%0A            'data': data,%0A        %7D)%0A%0A    def get_action_response(self):%0A        if self.action not in self.allowed_actions:%0A            raise AsyncHandlerError(%22Action '%25s' is not allowed.%22 %25 self.action)%0A        response = getattr(self, '%25s_response' %25 self.action)%0A        return self._fmt_success(response)%0A%0A    def get_response(self):%0A        try:%0A            response = self.get_action_response()%0A        except AsyncHandlerError as e:%0A            response = self._fmt_error(e)%0A        except TypeError as e:%0A            response = self._fmt_error(e)%0A        return HttpResponse(response, content_type='application/json')%0A

add BaseAsyncHandler for handling async post requests in a view