版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010042585/article/details/79892073
1、首先需要安装django-mptt
python manger.py Django-mptt
2、models.py如下:
from django.db
import models
from mptt.models
import MPTTModel
class Area(MPTTModel):
name = models.CharField(
'模块名称'
,
max_length=
50
,
unique=
True)
parent_area = models.ForeignKey(
'self'
,
verbose_name=
'父节点'
,
null=
True,
blank=
True,
related_name=
'children')
community = models.TextField(
'内容'
,
null=
True,
blank=
True)
class Meta:
verbose_name =
'表名'
verbose_name_plural = verbose_name
class MPTTMeta:
parent_attr =
'parent_area'
def
__str__(
self):
return
self.name
3、views.py如下:
def
help(request):
nodes = models.Area.objects.all()
return render(request
,
'help.html'
, {
'nodes': nodes})
4、html页面代码如下:
<div
class=
"tree well"
>
<ul>
<li
class=
"parent_li"
style=
"
display:
list-item"
>
<span
title=
"折叠此级"
>
<i
class=
"glyphicon glyphicon-folder-open glyphicon-minus-sign"
></i>
商贸版
</span>
<ul>
{%
recursetree
nodes %}
{%
if
node.
is_leaf_node %}
<li
class=
"parent_li"
style=
"
display:
none"
>
<span
title=
"折叠此级"
>
<i
class=
"glyphicon glyphicon-minus-sign"
></i>
{{
node.
name }}
</span>
</li>
{%
else %}
<li
class=
"parent_li"
style=
"
display:
none"
>
<span
title=
"折叠此级"
>
<i
class=
"glyphicon glyphicon-minus-sign"
></i>
{{
node.
name }}
</span>
<ul>
{{
children }}
</ul>
</li>
{%
endif %}
{%
endrecursetree %}
</ul>
</ul>
</div>
5、相关js代码
<script
type=
"text/javascript"
>
$(
function(){
$(
'.
tree
li
:has(ul)').
addClass(
'parent_li').
find(
' >
span
').
attr(
'title'
,
'折叠此级')
;
$(
'.
tree
li
.
parent_li
[
ltype
=month] >
span
, .
tree
li
.
parent_li
[
ltype
=year]:gt(0) >
span
').
each(
function (e){
var children =
$(
this).parent(
'
li
.
parent_li
').
find(
' >
ul
>
li
')
;
children.
hide(
'fast')
;
$(
this).
attr(
'title'
,
'展开此级').
find(
' >
i
').
addClass(
'glyphicon-plus-sign').
removeClass(
'glyphicon-minus-sign')
;
})
;
$(
'.
tree
li
.
parent_li
>
span
').
on(
'click'
,
function (e) {
var children =
$(
this).parent(
'
li
.
parent_li
').
find(
' >
ul
>
li
')
;
if (children.
is(
":visible")) {
children.
hide(
'fast')
;
$(
this).
attr(
'title'
,
'展开此级').
find(
' >
i
').
addClass(
'glyphicon-plus-sign').
removeClass(
'glyphicon-minus-sign')
;
}
else {
children.
show(
'fast')
;
$(
this).
attr(
'title'
,
'折叠此级').
find(
' >
i
').
addClass(
'glyphicon-minus-sign').
removeClass(
'glyphicon-plus-sign')
;
}
e.
stopPropagation()
;
})
;
})
;
</script>
效果图