Search code examples
djangotreeviewdjango-templates

tree structure of parent child relation in django templates


how do i implement the tree structure in django templates with out using django-mptt.

i have model.

class Person(TimeStampedModel):
    name  = models.CharField(max_length=32)
    parent      = models.ForeignKey('self', null=True, blank=True, related_name='children')

now i want ..

 Parent
    Child 1
         subchild 1.1
         subchild 1.2
             nextsubchild 1.2.1
    Child 2
    Child 3

there names should be click able to show their profile.


Solution

  • from Django while loop question and

    http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

    # view.py
    
    @register.inclusion_tag('children.html')
    def children_tag(person):
        children = person.children.all()
        return {'children': children}
    
    # children.html
    
    <ul>
        {% for child in children %}
        <li> <a href="{{ child.get_absolute_url }}">{{ child }}</a></li>
            {% if child.children.count > 0 %}
            {% children_tag child %}
            {% endif %}
        {% endfor %}
    </ul>
    
    
    # your template
    
    {% children_tag parent %}