self-related objects list with links

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, TemplateSyntaxError, Node

register = Library()

class RelatedNode(Node):
    def __init__(self, object_list, viewname):
        self.object_list = Variable(object_list)
        self.viewname = viewname

    def render(self, context):
        def node(object):
            try:
                reversed = reverse(self.viewname, args=[object.id])
            except NoReverseMatch:
                return '<li>%s</li>' % object

            return '<li><a href="%s">%s</li>' % (reversed, object)

        def recursive(object):
            if object.child_set.all():
                output.append('<ul>')
                for object in object.child_set.all():
                    output.append(node(object))
                    recursive(object)
                output.append('</ul>')

        output = []
        for object in self.object_list.resolve(context):
            if not object.parent:
                output.append(node(object))
                recursive(object)

        return '\n'.join(output)

def related_linked_list(parser, token):
    bits = token.contents.split()
    if len(bits) != 3:
        raise TemplateSyntaxError, "'%s' tag takes exactly 2 arguments" % bits[0]
    return RelatedNode(bits[1], bits[2])

register.tag(related_linked_list)

More like this

  1. Self-referencing Foreign Key Infinite Loop by minarets 6 years, 7 months ago
  2. Accessing URL variable from within a Form by blacktav 7 months, 3 weeks ago
  3. outliner template tag by showell 5 years ago
  4. Lightweight querysets by sardarnl 10 months, 1 week ago
  5. Manager for something like __inall by apollo13 6 years, 5 months ago

Comments

areich (on December 18, 2011):

How do I call this? In other words, what does the view 'view_category' look like to be callable via this tag? urls.py?

Thanks!

#

areich (on December 18, 2011):

via stackoverflow:

In your url conf:

url(r'^some-category/(\d+)/$', some_category_view, name="my-category-view") For your tag, the view_category == "my-category-view"

...So that ultimately the reverse is calling:

reversed = reverse("my-category-view", args=[object.id])

the view returns an HttpResponse

#

(Forgotten your password?)