tags:

views:

174

answers:

1

I want to access the latest object a django-mptt tree.

Is it possible to do this from a django template?

+1  A: 

In python code, you can use the get_children method. This should work:

children = node.get_children()
if children:
    last_child = list(children)[-1]

To use this in a template, you'd need to write a simple template tag:

from django import template
register = template.Library()

@register.simple_tag
def last_child(node):
    children = node.get_children()
    if children:
        return list(children)[-1]
    else:
        return ""

Have a look at the Django documentation to find out how to integrate this tag into your project.

piquadrat
This looks great, but I get this error: Caught an exception while rendering: Negative indexing is not supported.
Hobhouse
sorry, forgot to turn the queryset into a list. Fixed
piquadrat
great, now this works! :-)small note if anyone copies this code: return = list(children)[-1] in the simple_tag should of course be return list(children)[-1]
Hobhouse
again, sorry for not testing my code before answering. My train was just about to enter the train station and I hadn't time to test it
piquadrat