utils.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from importlib import import_module
  2. import json
  3. from django.core.serializers.json import DjangoJSONEncoder
  4. from django.http import HttpResponse
  5. from django.core.urlresolvers import reverse, resolve
  6. from django.contrib import admin
  7. from django.contrib.admin import AdminSite
  8. from django.utils.encoding import force_text
  9. from django.utils.encoding import smart_text
  10. from django.utils.functional import Promise
  11. from jet import settings
  12. class JsonResponse(HttpResponse):
  13. """
  14. An HTTP response class that consumes data to be serialized to JSON.
  15. :param data: Data to be dumped into json. By default only ``dict`` objects
  16. are allowed to be passed due to a security flaw before EcmaScript 5. See
  17. the ``safe`` parameter for more information.
  18. :param encoder: Should be an json encoder class. Defaults to
  19. ``django.core.serializers.json.DjangoJSONEncoder``.
  20. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  21. to ``True``.
  22. """
  23. def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
  24. if safe and not isinstance(data, dict):
  25. raise TypeError('In order to allow non-dict objects to be '
  26. 'serialized set the safe parameter to False')
  27. kwargs.setdefault('content_type', 'application/json')
  28. data = json.dumps(data, cls=encoder)
  29. super(JsonResponse, self).__init__(content=data, **kwargs)
  30. def get_app_list(context):
  31. template_response = get_admin_site(context.get('current_app', '')).index(context['request'])
  32. try:
  33. return template_response.context_data['app_list']
  34. except Exception:
  35. return None
  36. def get_admin_site(current_app):
  37. try:
  38. resolver_match = resolve(reverse('%s:index' % current_app))
  39. for func_closure in resolver_match.func.func_closure:
  40. if isinstance(func_closure.cell_contents, AdminSite):
  41. return func_closure.cell_contents
  42. except:
  43. pass
  44. return admin.site
  45. def get_admin_site_name(context):
  46. return get_admin_site(context).name
  47. def get_current_dashboard(location):
  48. if location == 'index':
  49. path = settings.JET_INDEX_DASHBOARD
  50. elif location == 'app_index':
  51. path = settings.JET_APP_INDEX_DASHBOARD
  52. else:
  53. raise ValueError('Unknown dashboard location: %s' % location)
  54. module, cls = path.rsplit('.', 1)
  55. module = import_module(module)
  56. index_dashboard_cls = getattr(module, cls)
  57. return index_dashboard_cls
  58. class LazyEncoder(json.JSONEncoder):
  59. def default(self, obj):
  60. if isinstance(obj, Promise):
  61. return force_text(obj)
  62. return obj
  63. def get_model_instance_label(instance):
  64. if getattr(instance, "related_label", None):
  65. return instance.related_label()
  66. return smart_text(instance)