Answer the question
In order to leave comments, you need to log in
Get slug in children mptt?
I use MPTT to display categories hierarchically.
My model.
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE, db_index=True)
slug = models.SlugField()
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
unique_together = (('parent', 'slug',))
verbose_name_plural = 'categories'
def get_slug_list(self):
try:
ancestors = self.get_ancestors(include_self=True)
except:
ancestors = []
else:
ancestors = [ i.slug for i in ancestors]
slugs = []
for i in range(len(ancestors)):
slugs.append('/'.join(ancestors[:i+1]))
return slugs
def __str__(self):
return self.name
category = Category.objects.all()
context {'category':category}
{% load mptt_tags %}
<ul>
{% recursetree category %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
Answer the question
In order to leave comments, you need to log in
I did it
{% recursetree categories %}
<!-- блок аккордеон -->
<div class="accordion">
<section class="accordion_item">
<h3 class="title_block"><strong>{{ node.name }}</strong></h3>
{% if not node.is_leaf_node %}
{% for child in node.children.all %}
<div class="info"><hr>
<ul>
<li class="info_item"><a href="{% url 'shop:catlist' child.slug %}"><u>{{ child.name }}</u></a></li>
</ul>
{% recursetree child.children.all %}
<ul>
<li class="info"><a href="{% url 'shop:shop-list' node.slug %}">{{ node.name }}</a></li>
</ul>
{% endrecursetree %}
</div>
{% endfor %}
{% endif %}
</section>
</div>
<!-- конец блока аккордеон -->
{% endrecursetree %}
Open the documentation and see there
The context variable children
contains the text resulting from the recursive rendering of the template located inside the tag recursetree
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question