# -*- coding: utf-8 -*-
#
# django_pam/accounts/view_mixins.py
#
"""
Dynamic Column view mixins.
"""
__docformat__ = "restructuredtext en"
import logging
from django.http import JsonResponse
log = logging.getLogger('django_pam.accounts.views')
[docs]
class JSONResponseMixin:
"""
A mixin that can be used to render a JSON response.
"""
[docs]
def render_to_json_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
:param context: The template rendering context.
:type context: See `Django Context <https://docs.djangoproject.com/en/dev/ref/templates/api/#playing-with-context-objects>`_.
:param response_kwargs: Response keywords arguments.
:rtype: See `Django response_class <https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin.response_class>`_.
"""
return JsonResponse(self.get_data(**context), **response_kwargs)
[docs]
def get_data(self, **context):
"""
Returns an object that will be serialized as JSON by json.dumps().
:param context: Context added to the JSON response.
:type context: dict
:rtype: dict -- Updated context
"""
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return context
[docs]
def is_ajax(self):
return self.request.headers.get('x-requested-with') == 'XMLHttpRequest'
[docs]
class AjaxableResponseMixin:
"""
Mixin to add AJAX support to a form. Must be used with an object-based
FormView (e.g. CreateView)
"""
[docs]
def get_data(self, **context):
"""
Returns an object that will be serialized as JSON by json.dumps().
:param context: Context added to the JSON response.
:type context: dict
:rtype: dict -- Updated context
"""
context.update({'pk': self.object.pk})
return context
[docs]
def is_ajax(self):
return self.request.headers.get('x-requested-with') == 'XMLHttpRequest'