modules.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import json
  2. from django import forms
  3. from django.contrib.admin.models import LogEntry
  4. from django.db.models import Q
  5. from django.template.loader import render_to_string
  6. from django.utils.translation import ugettext_lazy as _
  7. from jet.utils import get_app_list, LazyEncoder
  8. import datetime
  9. class DashboardModule(object):
  10. template = 'jet/dashboard/module.html'
  11. enabled = True
  12. draggable = True
  13. collapsible = True
  14. deletable = True
  15. show_title = True
  16. title = ''
  17. title_url = None
  18. css_classes = None
  19. pre_content = None
  20. post_content = None
  21. children = None
  22. settings_form = None
  23. child_form = None
  24. child_name = None
  25. child_name_plural = None
  26. settings = None
  27. column = None
  28. order = None
  29. ajax_load = False
  30. class Media:
  31. css = ()
  32. js = ()
  33. def __init__(self, title=None, model=None, context=None, **kwargs):
  34. if title is not None:
  35. self.title = title
  36. self.model = model
  37. self.context = context or {}
  38. for key in kwargs:
  39. if hasattr(self.__class__, key):
  40. setattr(self, key, kwargs[key])
  41. self.children = self.children or []
  42. if self.model:
  43. self.load_from_model()
  44. def fullname(self):
  45. return self.__module__ + "." + self.__class__.__name__
  46. def load_settings(self, settings):
  47. pass
  48. def load_children(self, children):
  49. self.children = children
  50. def store_children(self):
  51. return False
  52. def settings_dict(self):
  53. pass
  54. def dump_settings(self, settings=None):
  55. settings = settings or self.settings_dict()
  56. if settings:
  57. return json.dumps(settings, cls=LazyEncoder)
  58. else:
  59. return ''
  60. def dump_children(self):
  61. if self.store_children():
  62. return json.dumps(self.children, cls=LazyEncoder)
  63. else:
  64. return ''
  65. def load_from_model(self):
  66. self.title = self.model.title
  67. if self.model.settings:
  68. try:
  69. self.settings = json.loads(self.model.settings)
  70. self.load_settings(self.settings)
  71. except ValueError:
  72. pass
  73. if self.store_children() and self.model.children:
  74. try:
  75. children = json.loads(self.model.children)
  76. self.load_children(children)
  77. except ValueError:
  78. pass
  79. def init_with_context(self, context):
  80. pass
  81. def get_context_data(self):
  82. context = self.context
  83. context.update({
  84. 'module': self
  85. })
  86. return context
  87. def render(self):
  88. self.init_with_context(self.context)
  89. return render_to_string(self.template, self.get_context_data())
  90. class LinkListItemForm(forms.Form):
  91. url = forms.CharField(label=_('URL'))
  92. title = forms.CharField(label=_('Title'))
  93. external = forms.BooleanField(label=_('External link'), required=False)
  94. class LinkListSettingsForm(forms.Form):
  95. layout = forms.ChoiceField(label=_('Layout'), choices=(('stacked', _('Stacked')), ('inline', _('Inline'))))
  96. class LinkList(DashboardModule):
  97. title = _('Links')
  98. template = 'jet/dashboard/modules/link_list.html'
  99. layout = 'stacked'
  100. settings_form = LinkListSettingsForm
  101. child_form = LinkListItemForm
  102. child_name = _('Link')
  103. child_name_plural = _('Links')
  104. def __init__(self, title=None, children=list(), **kwargs):
  105. children = map(self.parse_link, children)
  106. kwargs.update({'children': children})
  107. super(LinkList, self).__init__(title, **kwargs)
  108. def settings_dict(self):
  109. return {
  110. 'layout': self.layout
  111. }
  112. def load_settings(self, settings):
  113. self.layout = settings.get('layout', self.layout)
  114. def store_children(self):
  115. return True
  116. def parse_link(self, link):
  117. if isinstance(link, (tuple, list)):
  118. link_dict = {'title': link[0], 'url': link[1]}
  119. if len(link) >= 3:
  120. link_dict['external'] = link[2]
  121. return link_dict
  122. elif isinstance(link, (dict,)):
  123. return link
  124. class AppList(DashboardModule):
  125. title = _('Applications')
  126. template = 'jet/dashboard/modules/app_list.html'
  127. models = None
  128. exclude = None
  129. hide_empty = True
  130. def settings_dict(self):
  131. return {
  132. 'models': self.models,
  133. 'exclude': self.exclude
  134. }
  135. def load_settings(self, settings):
  136. self.models = settings.get('models')
  137. self.exclude = settings.get('exclude')
  138. def init_with_context(self, context):
  139. app_list = get_app_list(context)
  140. app_to_remove = []
  141. for app in app_list:
  142. app['models'] = filter(
  143. lambda model: self.models is None or model['object_name'] in self.models or app['app_label'] + '.*' in self.models,
  144. app['models']
  145. )
  146. app['models'] = filter(
  147. lambda model: self.exclude is None or model['object_name'] not in self.exclude and app['app_label'] + '.*' not in self.exclude,
  148. app['models']
  149. )
  150. if self.hide_empty and len(app['models']) == 0:
  151. app_to_remove.append(app)
  152. for app in app_to_remove:
  153. app_list.remove(app)
  154. self.children = app_list
  155. class ModelList(DashboardModule):
  156. title = _('Models')
  157. template = 'jet/dashboard/modules/model_list.html'
  158. models = None
  159. exclude = None
  160. hide_empty = True
  161. def settings_dict(self):
  162. return {
  163. 'models': self.models,
  164. 'exclude': self.exclude
  165. }
  166. def load_settings(self, settings):
  167. self.models = settings.get('models')
  168. self.exclude = settings.get('exclude')
  169. def init_with_context(self, context):
  170. app_list = get_app_list(context)
  171. models = []
  172. for app in app_list:
  173. app['models'] = filter(
  174. lambda model: self.models is None or model['object_name'] in self.models or app['app_label'] + '.*' in self.models,
  175. app['models']
  176. )
  177. app['models'] = filter(
  178. lambda model: self.exclude is None or model['object_name'] not in self.exclude and app['app_label'] + '.*' not in self.exclude,
  179. app['models']
  180. )
  181. models.extend(app['models'])
  182. self.children = models
  183. class RecentActionsSettingsForm(forms.Form):
  184. limit = forms.IntegerField(label=_('Items limit'), min_value=1)
  185. class RecentActions(DashboardModule):
  186. title = _('Recent Actions')
  187. template = 'jet/dashboard/modules/recent_actions.html'
  188. limit = 10
  189. include_list = None
  190. exclude_list = None
  191. settings_form = RecentActionsSettingsForm
  192. user = None
  193. def __init__(self, title=None, limit=10, **kwargs):
  194. kwargs.update({'limit': limit})
  195. super(RecentActions, self).__init__(title, **kwargs)
  196. def settings_dict(self):
  197. return {
  198. 'limit': self.limit,
  199. 'include_list': self.include_list,
  200. 'exclude_list': self.exclude_list,
  201. 'user': self.user
  202. }
  203. def load_settings(self, settings):
  204. self.limit = settings.get('limit', self.limit)
  205. self.include_list = settings.get('include_list')
  206. self.exclude_list = settings.get('exclude_list')
  207. self.user = settings.get('user', None)
  208. def init_with_context(self, context):
  209. def get_qset(list):
  210. qset = None
  211. for contenttype in list:
  212. try:
  213. app_label, model = contenttype.split('.')
  214. if model == '*':
  215. current_qset = Q(
  216. content_type__app_label=app_label
  217. )
  218. else:
  219. current_qset = Q(
  220. content_type__app_label=app_label,
  221. content_type__model=model
  222. )
  223. except:
  224. raise ValueError('Invalid contenttype: "%s"' % contenttype)
  225. if qset is None:
  226. qset = current_qset
  227. else:
  228. qset = qset | current_qset
  229. return qset
  230. qs = LogEntry.objects
  231. if self.user:
  232. qs = qs.filter(
  233. user__pk=int(self.user)
  234. )
  235. if self.include_list:
  236. qs = qs.filter(get_qset(self.include_list))
  237. if self.exclude_list:
  238. qs = qs.exclude(get_qset(self.exclude_list))
  239. self.children = qs.select_related('content_type', 'user')[:int(self.limit)]
  240. class FeedSettingsForm(forms.Form):
  241. limit = forms.IntegerField(label=_('Items limit'), min_value=1)
  242. feed_url = forms.URLField(label=_('Feed URL'))
  243. class Feed(DashboardModule):
  244. title = _('RSS Feed')
  245. template = 'jet/dashboard/modules/feed.html'
  246. feed_url = None
  247. limit = None
  248. settings_form = FeedSettingsForm
  249. ajax_load = True
  250. def __init__(self, title=None, feed_url=None, limit=None, **kwargs):
  251. kwargs.update({'feed_url': feed_url, 'limit': limit})
  252. super(Feed, self).__init__(title, **kwargs)
  253. def settings_dict(self):
  254. return {
  255. 'feed_url': self.feed_url,
  256. 'limit': self.limit
  257. }
  258. def load_settings(self, settings):
  259. self.feed_url = settings.get('feed_url')
  260. self.limit = settings.get('limit')
  261. def init_with_context(self, context):
  262. if self.feed_url is not None:
  263. try:
  264. import feedparser
  265. feed = feedparser.parse(self.feed_url)
  266. if self.limit is not None:
  267. entries = feed['entries'][:self.limit]
  268. else:
  269. entries = feed['entries']
  270. for entry in entries:
  271. try:
  272. entry.date = datetime.date(*entry.published_parsed[0:3])
  273. except:
  274. pass
  275. self.children.append(entry)
  276. except ImportError:
  277. self.children.append({
  278. 'title': _('You must install the FeedParser python module'),
  279. 'warning': True,
  280. })
  281. else:
  282. self.children.append({
  283. 'title': _('You must provide a valid feed URL'),
  284. 'warning': True,
  285. })