我正在使用django(3.1.2)在Python3.7中开发一个Web应用程序。我想创建一个将在某些路径下列出文件夹和文件的应用程序。我想用django.mptt来做。
我在settings.py中声明了路径:
MAIN_DIRECTORY = r'D:\imgs'
我创建了以下模型:
class Folder(MPTTModel):
name = models.CharField(max_length=30, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
并查看:
class MainView(TemplateView):
template_name = "main.html"
def get_directories(self):
path = settings.MAIN_DIRECTORY
self.tree = self.get_folder_from_db(path, None)
for root, dirs, files in os.walk(path):
if root == path:
continue
root_folder = self.get_folder_from_db(name=root, parent=self.tree)
for d in dirs:
if os.path.isdir(d):
tmp = self.get_folder_from_db(name=d, parent=root_folder)
def get_folder_from_db(self, name, parent):
try:
obj = Folder.objects.get(name=name, parent=parent)
except Folder.DoesNotExist:
obj = Folder(name=name, parent=parent)
obj.save()
return obj
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
self.get_directories()
context['tree'] = [self.tree]
return context
当然还有模板(从mptt教程复制):
{% extends 'base.html' %}
{% load mptt_tags %}
{% block content %}
<h2>Main page</h2>
<ul class="root">
{% recursetree tree%}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
{% endblock %}
我知道树结构是正确的,因为我可以在django admin上检查它,并在视图中列出它。但是render html只包含一个
编辑
我换行
context['tree'] = [self.tree]
到
context['tree'] = Folder.objects.all()
有效。但是我不明白为什么。