utils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import datetime
  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 smart_text
  9. from jet import settings
  10. from django.contrib import messages
  11. from django.utils.encoding import force_text
  12. from django.utils.functional import Promise
  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. class LazyDateTimeEncoder(json.JSONEncoder):
  49. def default(self, obj):
  50. if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
  51. return obj.isoformat()
  52. elif isinstance(obj, Promise):
  53. return force_text(obj)
  54. return json.JSONEncoder.default(self, obj)
  55. def get_model_instance_label(instance):
  56. if getattr(instance, "related_label", None):
  57. return instance.related_label()
  58. return smart_text(instance)
  59. class SuccessMessageMixin(object):
  60. """
  61. Adds a success message on successful form submission.
  62. """
  63. success_message = ''
  64. def form_valid(self, form):
  65. response = super(SuccessMessageMixin, self).form_valid(form)
  66. success_message = self.get_success_message(form.cleaned_data)
  67. if success_message:
  68. messages.success(self.request, success_message)
  69. return response
  70. def get_success_message(self, cleaned_data):
  71. return self.success_message % cleaned_data