Django-mptt tree model returns empty children in template using recursetree
I am using Django 3.2 and django-mppt 0.13.4
This is my (simplified) model:
/path/to/myapp/models.py
class Comment(MPTTModel, MyTimestampedModel):
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
content = models.TextField(default='')
markdown_content = models.TextField(default='')
attachment = models.ImageField()
class MPTTMeta:
order_insertion_by = ['created_at']
class Meta:
permissions = [('can_moderate_comments', 'Can moderate comments'),
('can_attach_file', 'Can attach file'),]
class Commentable(models.Model, Foo):
accept_comments = models.BooleanField(default=True, blank=True)
comments = GenericRelation(Comment)
# ... other fields
class Article(Commentable, FooBar):
pass
/path/to/myapp/views.py
class ArticleDetailView(DetailView): model = Article
def get_context_data(self, **kwargs):
context = super(ArticleDetailView, self).get_context_data(**kwargs)
article = self.get_object()
# ....
context['comments'] = article.comments.all()
<ul class="root">
{% recursetree nodes %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
/path/to/myapp/templates/myapp/article_detail.html
{% recursetree comments %}
<li>
{{ node.markdown_content }}
{% if not node.is_leaf_node %}
{{node.get_descendant_count}} Replies
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
I add three comments to the database (via the shell command), with the following heirarchical relation:
Comment 1 (id=1)
Reply To Comment 1 (id=3)
Reply To Reply to Comment 1 (id=4)
Comment 2 (id=2)
When I type the following at the command prompt:
Comment.objects.filter(id=1).get_children()
=> 1
Comment.objects.filter(id=1).get_descendent_count()
=> 2
However (focusing on only the first comment for now), in my template, although the node.get_descendant_count variable matches that obtained directly from the DB, the children is a null set in the template - whereas when accessing the database directly, the correct number of (direct) children is returned.
Why is the template not returning the comment's children correctly - and how do I fix this?
No need to fix because it works correctly. Please read the following notes carefully from https://django-mptt.readthedocs.io/en/latest/templates.html
Note the special variables
nodeandchildren. These are magically inserted into your context while you’re inside therecursetreetag.
nodeis an instance of your MPTT model.
children: This variable holds the rendered HTML for the children of node.
And got a comment from mptt_tags.py.
Iterates over the nodes in the tree, and renders the contained block for each node. This tag will recursively render children into the template variable
{{ children }}. Only one database query is required (childrenare cached for the whole tree)