utils.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from django.contrib import messages
  13. class JsonResponse(HttpResponse):
  14. """
  15. An HTTP response class that consumes data to be serialized to JSON.
  16. :param data: Data to be dumped into json. By default only ``dict`` objects
  17. are allowed to be passed due to a security flaw before EcmaScript 5. See
  18. the ``safe`` parameter for more information.
  19. :param encoder: Should be an json encoder class. Defaults to
  20. ``django.core.serializers.json.DjangoJSONEncoder``.
  21. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  22. to ``True``.
  23. """
  24. def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
  25. if safe and not isinstance(data, dict):
  26. raise TypeError('In order to allow non-dict objects to be '
  27. 'serialized set the safe parameter to False')
  28. kwargs.setdefault('content_type', 'application/json')
  29. data = json.dumps(data, cls=encoder)
  30. super(JsonResponse, self).__init__(content=data, **kwargs)
  31. def get_app_list(context):
  32. template_response = get_admin_site(context.get('current_app', '')).index(context['request'])
  33. try:
  34. return template_response.context_data['app_list']
  35. except Exception:
  36. return None
  37. def get_admin_site(current_app):
  38. try:
  39. resolver_match = resolve(reverse('%s:index' % current_app))
  40. for func_closure in resolver_match.func.func_closure:
  41. if isinstance(func_closure.cell_contents, AdminSite):
  42. return func_closure.cell_contents
  43. except:
  44. pass
  45. return admin.site
  46. def get_admin_site_name(context):
  47. return get_admin_site(context).name
  48. def get_current_dashboard(location):
  49. if location == 'index':
  50. path = settings.JET_INDEX_DASHBOARD
  51. elif location == 'app_index':
  52. path = settings.JET_APP_INDEX_DASHBOARD
  53. else:
  54. raise ValueError('Unknown dashboard location: %s' % location)
  55. module, cls = path.rsplit('.', 1)
  56. module = import_module(module)
  57. index_dashboard_cls = getattr(module, cls)
  58. return index_dashboard_cls
  59. class LazyEncoder(json.JSONEncoder):
  60. def default(self, obj):
  61. if isinstance(obj, Promise):
  62. return force_text(obj)
  63. return obj
  64. def get_model_instance_label(instance):
  65. if getattr(instance, "related_label", None):
  66. return instance.related_label()
  67. return smart_text(instance)
  68. class SuccessMessageMixin(object):
  69. """
  70. Adds a success message on successful form submission.
  71. """
  72. success_message = ''
  73. def form_valid(self, form):
  74. response = super(SuccessMessageMixin, self).form_valid(form)
  75. success_message = self.get_success_message(form.cleaned_data)
  76. if success_message:
  77. messages.success(self.request, success_message)
  78. return response
  79. def get_success_message(self, cleaned_data):
  80. return self.success_message % cleaned_data