【发布时间】:2015-08-12 10:42:39
【问题描述】:
我正在尝试为 django-cms 实现一个显示链接树的插件。我想要做的是根据用户在我的 CMS 中选择的配置过滤此树。因此,根据他在配置中选择的节点,我希望能够仅显示该子树。
这是我的models.py
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from cms.models.pluginmodel import CMSPlugin
class Section(MPTTModel):
name = models.CharField(max_length=25, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return self.name
class SectionConfig(CMSPlugin):
root_shown = models.ForeignKey("Section")
title = models.CharField(default="Usefull Links", max_length=25)
这是我的 cms_plugins.py:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from links_plugin.models import Section, SectionConfig
class LinksPlugin(CMSPluginBase):
name = _("Links Tree Plugin")
model = SectionConfig
render_template = "links.html"
cache = False
def render(self, context, instance, placeholder):
context['instance'] = instance
context['nodes'] = Section.objects.all()
return context
plugin_pool.register_plugin(LinksPlugin)
这是我的模板/links.html
<div class='container-fluid'>
<h1>Liens Utiles</h1>
{% load mptt_tags %}
<ul class="root">
{% recursetree nodes %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
</div>
所以我的问题是为我的上下文提供正确的节点集。所以在我的 cms_plugins.py id 喜欢改变
context['nodes'] = Section.objects.all()
到一个过滤器,它将基于我的构建子树
root_shown = models.ForeignKey("Section")
问题是我不知道如何使用 FK 来引用我的 Section 对象并找到我的新根 Section。从那时起,我认为我可以使用 get_descendants(include_self=True) 来重建这个新的子树并显示该节点列表。我错了吗?如何引用我想要的节点?
如果可能的话,ELI5
【问题讨论】:
标签: django-models django-cms django-filter