django模板中父子关系的树状结构 [英] tree structure of parent child relation in django templates

查看:28
本文介绍了django模板中父子关系的树状结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 django-mptt 的情况下在 django 模板中实现树结构.

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

我有模型.

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

现在我想要..

 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.

推荐答案

来自 Django while loop 问题和

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 %}
    

这篇关于django模板中父子关系的树状结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆