utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import datetime
  2. import json
  3. from django.template import Context
  4. from django.utils import translation
  5. from jet import settings
  6. from jet.models import PinnedApplication
  7. try:
  8. from django.apps.registry import apps
  9. except ImportError:
  10. try:
  11. from django.apps import apps # Fix Django 1.7 import issue
  12. except ImportError:
  13. pass
  14. from django.core.serializers.json import DjangoJSONEncoder
  15. from django.http import HttpResponse
  16. from django.core.urlresolvers import reverse, resolve, NoReverseMatch
  17. from django.contrib.admin import AdminSite
  18. from django.utils.encoding import smart_text
  19. from django.utils.text import capfirst
  20. from django.contrib import messages
  21. from django.utils.encoding import force_text
  22. from django.utils.functional import Promise
  23. from django.contrib.admin.options import IncorrectLookupParameters
  24. from django.core import urlresolvers
  25. from django.contrib import admin
  26. from django.utils.translation import ugettext_lazy as _
  27. from django.utils.text import slugify
  28. from collections import OrderedDict
  29. class JsonResponse(HttpResponse):
  30. """
  31. An HTTP response class that consumes data to be serialized to JSON.
  32. :param data: Data to be dumped into json. By default only ``dict`` objects
  33. are allowed to be passed due to a security flaw before EcmaScript 5. See
  34. the ``safe`` parameter for more information.
  35. :param encoder: Should be an json encoder class. Defaults to
  36. ``django.core.serializers.json.DjangoJSONEncoder``.
  37. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  38. to ``True``.
  39. """
  40. def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
  41. if safe and not isinstance(data, dict):
  42. raise TypeError('In order to allow non-dict objects to be '
  43. 'serialized set the safe parameter to False')
  44. kwargs.setdefault('content_type', 'application/json')
  45. data = json.dumps(data, cls=encoder)
  46. super(JsonResponse, self).__init__(content=data, **kwargs)
  47. def get_app_list(context, order=True):
  48. admin_site = get_admin_site(context)
  49. request = context['request']
  50. app_dict = {}
  51. for model, model_admin in admin_site._registry.items():
  52. app_label = model._meta.app_label
  53. try:
  54. has_module_perms = model_admin.has_module_permission(request)
  55. except AttributeError:
  56. has_module_perms = request.user.has_module_perms(app_label) # Fix Django < 1.8 issue
  57. if has_module_perms:
  58. perms = model_admin.get_model_perms(request)
  59. # Check whether user has any perm for this module.
  60. # If so, add the module to the model_list.
  61. if True in perms.values():
  62. info = (app_label, model._meta.model_name)
  63. model_dict = {
  64. 'name': capfirst(model._meta.verbose_name_plural),
  65. 'object_name': model._meta.object_name,
  66. 'perms': perms,
  67. 'model_name': model._meta.model_name
  68. }
  69. if perms.get('change', False):
  70. try:
  71. model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=admin_site.name)
  72. except NoReverseMatch:
  73. pass
  74. if perms.get('add', False):
  75. try:
  76. model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=admin_site.name)
  77. except NoReverseMatch:
  78. pass
  79. if app_label in app_dict:
  80. app_dict[app_label]['models'].append(model_dict)
  81. else:
  82. try:
  83. name = apps.get_app_config(app_label).verbose_name
  84. except NameError:
  85. name = app_label.title()
  86. app_dict[app_label] = {
  87. 'name': name,
  88. 'app_label': app_label,
  89. 'app_url': reverse(
  90. 'admin:app_list',
  91. kwargs={'app_label': app_label},
  92. current_app=admin_site.name,
  93. ),
  94. 'has_module_perms': has_module_perms,
  95. 'models': [model_dict],
  96. }
  97. # Sort the apps alphabetically.
  98. app_list = list(app_dict.values())
  99. if order:
  100. app_list.sort(key=lambda x: x['name'].lower())
  101. # Sort the models alphabetically within each app.
  102. for app in app_list:
  103. app['models'].sort(key=lambda x: x['name'])
  104. return app_list
  105. def get_admin_site(context):
  106. try:
  107. current_resolver = resolve(context.get('request').path)
  108. index_resolver = resolve(reverse('%s:index' % current_resolver.namespaces[0]))
  109. if hasattr(index_resolver.func, 'admin_site'):
  110. return index_resolver.func.admin_site
  111. for func_closure in index_resolver.func.__closure__:
  112. if isinstance(func_closure.cell_contents, AdminSite):
  113. return func_closure.cell_contents
  114. except:
  115. pass
  116. return admin.site
  117. def get_admin_site_name(context):
  118. return get_admin_site(context).name
  119. class LazyDateTimeEncoder(json.JSONEncoder):
  120. def default(self, obj):
  121. if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
  122. return obj.isoformat()
  123. elif isinstance(obj, Promise):
  124. return force_text(obj)
  125. return self.encode(obj)
  126. def get_model_instance_label(instance):
  127. if getattr(instance, "related_label", None):
  128. return instance.related_label()
  129. return smart_text(instance)
  130. class SuccessMessageMixin(object):
  131. """
  132. Adds a success message on successful form submission.
  133. """
  134. success_message = ''
  135. def form_valid(self, form):
  136. response = super(SuccessMessageMixin, self).form_valid(form)
  137. success_message = self.get_success_message(form.cleaned_data)
  138. if success_message:
  139. messages.success(self.request, success_message)
  140. return response
  141. def get_success_message(self, cleaned_data):
  142. return self.success_message % cleaned_data
  143. def get_model_queryset(admin_site, model, request, preserved_filters=None):
  144. model_admin = admin_site._registry.get(model)
  145. try:
  146. changelist_url = urlresolvers.reverse('%s:%s_%s_changelist' % (
  147. admin_site.name,
  148. model._meta.app_label,
  149. model._meta.model_name
  150. ))
  151. except NoReverseMatch:
  152. return
  153. changelist_filters = None
  154. if preserved_filters:
  155. changelist_filters = preserved_filters.get('_changelist_filters')
  156. if changelist_filters:
  157. changelist_url += '?' + changelist_filters
  158. if model_admin:
  159. queryset = model_admin.get_queryset(request)
  160. else:
  161. queryset = model.objects
  162. list_display = model_admin.get_list_display(request)
  163. list_display_links = model_admin.get_list_display_links(request, list_display)
  164. list_filter = model_admin.get_list_filter(request)
  165. search_fields = model_admin.get_search_fields(request) \
  166. if hasattr(model_admin, 'get_search_fields') else model_admin.search_fields
  167. list_select_related = model_admin.get_list_select_related(request) \
  168. if hasattr(model_admin, 'get_list_select_related') else model_admin.list_select_related
  169. actions = model_admin.get_actions(request)
  170. if actions:
  171. list_display = ['action_checkbox'] + list(list_display)
  172. ChangeList = model_admin.get_changelist(request)
  173. try:
  174. cl = ChangeList(
  175. request, model, list_display, list_display_links, list_filter, model_admin.date_hierarchy, search_fields,
  176. list_select_related, model_admin.list_per_page, model_admin.list_max_show_all, model_admin.list_editable,
  177. model_admin)
  178. queryset = cl.get_queryset(request)
  179. except IncorrectLookupParameters:
  180. pass
  181. return queryset
  182. def get_possible_language_codes():
  183. language_code = translation.get_language()
  184. language_code = language_code.replace('_', '-').lower()
  185. language_codes = []
  186. # making dialect part uppercase
  187. split = language_code.split('-', 2)
  188. if len(split) == 2:
  189. language_code = '%s-%s' % (split[0].lower(), split[1].upper()) if split[0] != split[1] else split[0]
  190. language_codes.append(language_code)
  191. # adding language code without dialect part
  192. if len(split) == 2:
  193. language_codes.append(split[0].lower())
  194. return language_codes
  195. def get_original_menu_items(context):
  196. if context.get('user') and context['user'].is_authenticated():
  197. pinned_apps = PinnedApplication.objects.filter(user=context['user'].pk).values_list('app_label', flat=True)
  198. else:
  199. pinned_apps = []
  200. original_app_list = get_app_list(context)
  201. return map(lambda app: {
  202. 'app_label': app['app_label'],
  203. 'url': app['app_url'],
  204. 'url_blank': False,
  205. 'label': app.get('name', capfirst(_(app['app_label']))),
  206. 'has_perms': app.get('has_module_perms', False),
  207. 'models': list(map(lambda model: {
  208. 'url': model.get('admin_url'),
  209. 'url_blank': False,
  210. 'name': model['model_name'],
  211. 'object_name': model['object_name'],
  212. 'label': model.get('name', model['object_name']),
  213. 'has_perms': any(model.get('perms', {}).values()),
  214. }, app['models'])),
  215. 'pinned': app['app_label'] in pinned_apps,
  216. 'custom': False
  217. }, original_app_list)
  218. def get_menu_item_url(url, original_app_list):
  219. if isinstance(url, dict):
  220. url_type = url.get('type')
  221. if url_type == 'app':
  222. return original_app_list[url['app_label']]['url']
  223. elif url_type == 'model':
  224. models = dict(map(
  225. lambda x: (x['name'], x['url']),
  226. original_app_list[url['app_label']]['models']
  227. ))
  228. return models[url['model']]
  229. elif url_type == 'reverse':
  230. return reverse(url['name'], args=url.get('args'), kwargs=url.get('kwargs'))
  231. elif isinstance(url, str):
  232. return url
  233. def get_menu_items(context):
  234. pinned_apps = PinnedApplication.objects.filter(user=context['user'].pk).values_list('app_label', flat=True)
  235. original_app_list = OrderedDict(map(lambda app: (app['app_label'], app), get_original_menu_items(context)))
  236. custom_app_list = settings.JET_SIDE_MENU_ITEMS
  237. custom_app_list_deprecated = settings.JET_SIDE_MENU_CUSTOM_APPS
  238. if custom_app_list not in (None, False):
  239. if isinstance(custom_app_list, dict):
  240. admin_site = get_admin_site(context)
  241. custom_app_list = custom_app_list.get(admin_site.name, [])
  242. app_list = []
  243. def get_menu_item_app_model(app_label, data):
  244. item = {'has_perms': True}
  245. if 'name' in data:
  246. parts = data['name'].split('.', 2)
  247. if len(parts) > 1:
  248. app_label, name = parts
  249. else:
  250. name = data['name']
  251. if app_label in original_app_list:
  252. models = dict(map(
  253. lambda x: (x['name'], x),
  254. original_app_list[app_label]['models']
  255. ))
  256. if name in models:
  257. item = models[name].copy()
  258. if 'label' in data:
  259. item['label'] = data['label']
  260. if 'url' in data:
  261. item['url'] = get_menu_item_url(data['url'], original_app_list)
  262. if 'url_blank' in data:
  263. item['url_blank'] = data['url_blank']
  264. if 'permissions' in data:
  265. item['has_perms'] = item.get('has_perms', True) and context['user'].has_perms(data['permissions'])
  266. return item
  267. def get_menu_item_app(data):
  268. app_label = data.get('app_label')
  269. if not app_label:
  270. if 'label' not in data:
  271. raise Exception('Custom menu items should at least have \'label\' or \'app_label\' key')
  272. app_label = 'custom_%s' % slugify(data['label'], allow_unicode=True)
  273. if app_label in original_app_list:
  274. item = original_app_list[app_label].copy()
  275. else:
  276. item = {'app_label': app_label, 'has_perms': True}
  277. if 'label' in data:
  278. item['label'] = data['label']
  279. if 'models' in data:
  280. item['models'] = list(map(lambda x: get_menu_item_app_model(app_label, x), data['models']))
  281. if 'url' in data:
  282. item['url'] = get_menu_item_url(data['url'], original_app_list)
  283. if 'url_blank' in data:
  284. item['url_blank'] = data['url_blank']
  285. if 'permissions' in data:
  286. item['has_perms'] = item.get('has_perms', True) and context['user'].has_perms(data['permissions'])
  287. item['pinned'] = item['app_label'] in pinned_apps
  288. return item
  289. for data in custom_app_list:
  290. item = get_menu_item_app(data)
  291. app_list.append(item)
  292. elif custom_app_list_deprecated not in (None, False):
  293. app_dict = {}
  294. models_dict = {}
  295. for app in original_app_list.values():
  296. app_label = app['app_label']
  297. app_dict[app_label] = app
  298. for model in app['models']:
  299. if app_label not in models_dict:
  300. models_dict[app_label] = {}
  301. models_dict[app_label][model['object_name']] = model
  302. app['models'] = []
  303. app_list = []
  304. if isinstance(custom_app_list_deprecated, dict):
  305. admin_site = get_admin_site(context)
  306. custom_app_list_deprecated = custom_app_list_deprecated.get(admin_site.name, [])
  307. for item in custom_app_list_deprecated:
  308. app_label, models = item
  309. if app_label in app_dict:
  310. app = app_dict[app_label]
  311. for model_label in models:
  312. if model_label == '__all__':
  313. app['models'] = models_dict[app_label].values()
  314. break
  315. elif model_label in models_dict[app_label]:
  316. model = models_dict[app_label][model_label]
  317. app['models'].append(model)
  318. app_list.append(app)
  319. else:
  320. app_list = original_app_list.values()
  321. current_found = False
  322. for app in app_list:
  323. if not current_found:
  324. for model in app['models']:
  325. if not current_found and model.get('url') and context['request'].path.startswith(model['url']):
  326. model['current'] = True
  327. current_found = True
  328. else:
  329. model['current'] = False
  330. if not current_found and app.get('url') and context['request'].path.startswith(app['url']):
  331. app['current'] = True
  332. current_found = True
  333. else:
  334. app['current'] = False
  335. return app_list
  336. def context_to_dict(context):
  337. if isinstance(context, Context):
  338. flat = {}
  339. for d in context.dicts:
  340. flat.update(d)
  341. context = flat
  342. return context