Skip to content

Instantly share code, notes, and snippets.

@maxvyaznikov
Last active March 28, 2019 11:33
Show Gist options
  • Save maxvyaznikov/10527002 to your computer and use it in GitHub Desktop.
Save maxvyaznikov/10527002 to your computer and use it in GitHub Desktop.
Django: AJAX-friendly views
import json
from django.views.generic import TemplateView
from django.http import HttpResponse, HttpResponseBadRequest
from lib import ExtendedDjangoJSONEncoder
class RequestMixin(object):
def dispatch(self, request, *args, **kwargs):
self.request = request
return super(RequestMixin, self).dispatch(request, *args, **kwargs)
class AjaxView(RequestMixin, TemplateView):
"""
This class let makes separate handlers for ajax requests
(such as get_ajax, post_ajax, etc)
"""
def dispatch(self, request, *args, **kwargs):
method_name = request.method.lower()
if method_name in self.http_method_names:
handler = None
# check ajax request and call {method_name}_ajax class method
if request.is_ajax():
handler = getattr(self, u"{0}_ajax".format(method_name), None)
# then try standard behaviour
if not handler:
handler = getattr(self, method_name, self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
self.args = args
self.kwargs = kwargs
return handler(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(AjaxView, self).get_context_data(**kwargs)
context['request'] = self.request
return context
class JSONResponseMixin(object):
""" Create a JSON responses """
ajax_response_class = HttpResponse
def render_to_ajax_response(self, context, **response_kwargs):
response_kwargs['content_type'] = 'application/json'
return self.ajax_response_class(self.convert_to_json(context), **response_kwargs)
def render_to_ajax_error_response(self, error, field_name, ajax_response_class=HttpResponseBadRequest, **response_kwargs):
response_kwargs['content_type'] = 'application/json'
return ajax_response_class(self.convert_to_json({
'error': error,
'field': field_name,
}), **response_kwargs)
def convert_to_json(self, context):
if 'request' in context:
del context['request'] # django request isn't json-serializable
if 'view' in context:
del context['view'] # django view object isn't json-serializable
# return serializers.serialize('json', context);
return json.dumps(context, ensure_ascii=True, cls=ExtendedDjangoJSONEncoder) # See gist:10526923
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment