utils.py 16 KB

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