mptt.templatetags.mptt_tags: 131 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/mptt/templatetags/mptt_tags.py

Stats: 0 executed, 124 missed, 7 excluded, 189 ignored

  1. """
  2. Template tags for working with lists of model instances which represent
  3. trees.
  4. """
  5. from django import template
  6. from django.db.models import get_model
  7. from django.db.models.fields import FieldDoesNotExist
  8. from django.utils.encoding import force_unicode
  9. from django.utils.safestring import mark_safe
  10. from django.utils.translation import ugettext as _
  11. from mptt.utils import tree_item_iterator, drilldown_tree_for_node
  12. register = template.Library()
  13. ### ITERATIVE TAGS
  14. class FullTreeForModelNode(template.Node):
  15. def __init__(self, model, context_var):
  16. self.model = model
  17. self.context_var = context_var
  18. def render(self, context):
  19. cls = get_model(*self.model.split('.'))
  20. if cls is None:
  21. raise template.TemplateSyntaxError(
  22. _('full_tree_for_model tag was given an invalid model: %s') % self.model
  23. )
  24. context[self.context_var] = cls._tree_manager.all()
  25. return ''
  26. class DrilldownTreeForNodeNode(template.Node):
  27. def __init__(self, node, context_var, foreign_key=None, count_attr=None,
  28. cumulative=False):
  29. self.node = template.Variable(node)
  30. self.context_var = context_var
  31. self.foreign_key = foreign_key
  32. self.count_attr = count_attr
  33. self.cumulative = cumulative
  34. def render(self, context):
  35. # Let any VariableDoesNotExist raised bubble up
  36. args = [self.node.resolve(context)]
  37. if self.foreign_key is not None:
  38. app_label, model_name, fk_attr = self.foreign_key.split('.')
  39. cls = get_model(app_label, model_name)
  40. if cls is None:
  41. raise template.TemplateSyntaxError(
  42. _('drilldown_tree_for_node tag was given an invalid model: %s') % \
  43. '.'.join([app_label, model_name])
  44. )
  45. try:
  46. cls._meta.get_field(fk_attr)
  47. except FieldDoesNotExist:
  48. raise template.TemplateSyntaxError(
  49. _('drilldown_tree_for_node tag was given an invalid model field: %s') % fk_attr
  50. )
  51. args.extend([cls, fk_attr, self.count_attr, self.cumulative])
  52. context[self.context_var] = drilldown_tree_for_node(*args)
  53. return ''
  54. @register.tag
  55. def full_tree_for_model(parser, token):
  56. """
  57. Populates a template variable with a ``QuerySet`` containing the
  58. full tree for a given model.
  59. Usage::
  60. {% full_tree_for_model [model] as [varname] %}
  61. The model is specified in ``[appname].[modelname]`` format.
  62. Example::
  63. {% full_tree_for_model tests.Genre as genres %}
  64. """
  65. bits = token.contents.split()
  66. if len(bits) != 4:
  67. raise template.TemplateSyntaxError(_('%s tag requires three arguments') % bits[0])
  68. if bits[2] != 'as':
  69. raise template.TemplateSyntaxError(_("second argument to %s tag must be 'as'") % bits[0])
  70. return FullTreeForModelNode(bits[1], bits[3])
  71. @register.tag('drilldown_tree_for_node')
  72. def do_drilldown_tree_for_node(parser, token):
  73. """
  74. Populates a template variable with the drilldown tree for a given
  75. node, optionally counting the number of items associated with its
  76. children.
  77. A drilldown tree consists of a node's ancestors, itself and its
  78. immediate children. For example, a drilldown tree for a book
  79. category "Personal Finance" might look something like::
  80. Books
  81. Business, Finance & Law
  82. Personal Finance
  83. Budgeting (220)
  84. Financial Planning (670)
  85. Usage::
  86. {% drilldown_tree_for_node [node] as [varname] %}
  87. Extended usage::
  88. {% drilldown_tree_for_node [node] as [varname] count [foreign_key] in [count_attr] %}
  89. {% drilldown_tree_for_node [node] as [varname] cumulative count [foreign_key] in [count_attr] %}
  90. The foreign key is specified in ``[appname].[modelname].[fieldname]``
  91. format, where ``fieldname`` is the name of a field in the specified
  92. model which relates it to the given node's model.
  93. When this form is used, a ``count_attr`` attribute on each child of
  94. the given node in the drilldown tree will contain a count of the
  95. number of items associated with it through the given foreign key.
  96. If cumulative is also specified, this count will be for items
  97. related to the child node and all of its descendants.
  98. Examples::
  99. {% drilldown_tree_for_node genre as drilldown %}
  100. {% drilldown_tree_for_node genre as drilldown count tests.Game.genre in game_count %}
  101. {% drilldown_tree_for_node genre as drilldown cumulative count tests.Game.genre in game_count %}
  102. """
  103. bits = token.contents.split()
  104. len_bits = len(bits)
  105. if len_bits not in (4, 8, 9):
  106. raise template.TemplateSyntaxError(
  107. _('%s tag requires either three, seven or eight arguments') % bits[0])
  108. if bits[2] != 'as':
  109. raise template.TemplateSyntaxError(
  110. _("second argument to %s tag must be 'as'") % bits[0])
  111. if len_bits == 8:
  112. if bits[4] != 'count':
  113. raise template.TemplateSyntaxError(
  114. _("if seven arguments are given, fourth argument to %s tag must be 'with'") % bits[0])
  115. if bits[6] != 'in':
  116. raise template.TemplateSyntaxError(
  117. _("if seven arguments are given, sixth argument to %s tag must be 'in'") % bits[0])
  118. return DrilldownTreeForNodeNode(bits[1], bits[3], bits[5], bits[7])
  119. elif len_bits == 9:
  120. if bits[4] != 'cumulative':
  121. raise template.TemplateSyntaxError(
  122. _("if eight arguments are given, fourth argument to %s tag must be 'cumulative'") % bits[0])
  123. if bits[5] != 'count':
  124. raise template.TemplateSyntaxError(
  125. _("if eight arguments are given, fifth argument to %s tag must be 'count'") % bits[0])
  126. if bits[7] != 'in':
  127. raise template.TemplateSyntaxError(
  128. _("if eight arguments are given, seventh argument to %s tag must be 'in'") % bits[0])
  129. return DrilldownTreeForNodeNode(bits[1], bits[3], bits[6], bits[8], cumulative=True)
  130. else:
  131. return DrilldownTreeForNodeNode(bits[1], bits[3])
  132. @register.filter
  133. def tree_info(items, features=None):
  134. """
  135. Given a list of tree items, produces doubles of a tree item and a
  136. ``dict`` containing information about the tree structure around the
  137. item, with the following contents:
  138. new_level
  139. ``True`` if the current item is the start of a new level in
  140. the tree, ``False`` otherwise.
  141. closed_levels
  142. A list of levels which end after the current item. This will
  143. be an empty list if the next item is at the same level as the
  144. current item.
  145. Using this filter with unpacking in a ``{% for %}`` tag, you should
  146. have enough information about the tree structure to create a
  147. hierarchical representation of the tree.
  148. Example::
  149. {% for genre,structure in genres|tree_info %}
  150. {% if tree.new_level %}<ul><li>{% else %}</li><li>{% endif %}
  151. {{ genre.name }}
  152. {% for level in tree.closed_levels %}</li></ul>{% endfor %}
  153. {% endfor %}
  154. """
  155. kwargs = {}
  156. if features:
  157. feature_names = features.split(',')
  158. if 'ancestors' in feature_names:
  159. kwargs['ancestors'] = True
  160. return tree_item_iterator(items, **kwargs)
  161. @register.filter
  162. def tree_path(items, separator=' :: '):
  163. """
  164. Creates a tree path represented by a list of ``items`` by joining
  165. the items with a ``separator``.
  166. Each path item will be coerced to unicode, so a list of model
  167. instances may be given if required.
  168. Example::
  169. {{ some_list|tree_path }}
  170. {{ some_node.get_ancestors|tree_path:" > " }}
  171. """
  172. return separator.join([force_unicode(i) for i in items])
  173. ### RECURSIVE TAGS
  174. @register.filter
  175. def cache_tree_children(queryset):
  176. """
  177. Takes a list/queryset of model objects in MPTT left (depth-first) order,
  178. and caches the children on each node so that no further queries are needed.
  179. This makes it possible to have a recursively included template without worrying
  180. about database queries.
  181. Returns a list of top-level nodes.
  182. """
  183. current_path = []
  184. top_nodes = []
  185. if hasattr(queryset, 'order_by'):
  186. mptt_opts = queryset.model._mptt_meta
  187. tree_id_attr = mptt_opts.tree_id_attr
  188. left_attr = mptt_opts.left_attr
  189. queryset = queryset.order_by(tree_id_attr, left_attr)
  190. if queryset:
  191. root_level = None
  192. for obj in queryset:
  193. node_level = obj.get_level()
  194. if root_level is None:
  195. root_level = node_level
  196. if node_level < root_level:
  197. raise ValueError(_("cache_tree_children was passed nodes in the wrong order!"))
  198. obj._cached_children = []
  199. while len(current_path) > node_level - root_level:
  200. current_path.pop(-1)
  201. if node_level == root_level:
  202. top_nodes.append(obj)
  203. else:
  204. current_path[-1]._cached_children.append(obj)
  205. current_path.append(obj)
  206. return top_nodes
  207. class RecurseTreeNode(template.Node):
  208. def __init__(self, template_nodes, queryset_var):
  209. self.template_nodes = template_nodes
  210. self.queryset_var = queryset_var
  211. def _render_node(self, context, node):
  212. bits = []
  213. context.push()
  214. for child in node.get_children():
  215. context['node'] = child
  216. bits.append(self._render_node(context, child))
  217. context['node'] = node
  218. context['children'] = mark_safe(u''.join(bits))
  219. rendered = self.template_nodes.render(context)
  220. context.pop()
  221. return rendered
  222. def render(self, context):
  223. queryset = self.queryset_var.resolve(context)
  224. roots = cache_tree_children(queryset)
  225. bits = [self._render_node(context, node) for node in roots]
  226. return ''.join(bits)
  227. @register.tag
  228. def recursetree(parser, token):
  229. """
  230. Iterates over the nodes in the tree, and renders the contained block for each node.
  231. This tag will recursively render children into the template variable {{ children }}.
  232. Only one database query is required (children are cached for the whole tree)
  233. Usage:
  234. <ul>
  235. {% recursetree nodes %}
  236. <li>
  237. {{ node.name }}
  238. {% if not node.is_leaf_node %}
  239. <ul>
  240. {{ children }}
  241. </ul>
  242. {% endif %}
  243. </li>
  244. {% endrecursetree %}
  245. </ul>
  246. """
  247. bits = token.contents.split()
  248. if len(bits) != 2:
  249. raise template.TemplateSyntaxError(_('%s tag requires a queryset') % bits[0])
  250. queryset_var = template.Variable(bits[1])
  251. template_nodes = parser.parse(('endrecursetree',))
  252. parser.delete_first_token()
  253. return RecurseTreeNode(template_nodes, queryset_var)