Search code examples
djangodjango-mpttmptt

Using MPTT do get_children in templates (at runtime)


my template receives a variable called categories, and I want to list the categories that are "sons" of its father categories

this is my code in template

{% for category,structure in categories|tree_info %}
    {% if structure.new_level %}
<li><a href="/categories/{{ category.id }}/">{{ category.name }}</a> </li>   
    {% endif %}

    {% for level in structure.closed_levels %}
<li>{{level.name}}
    {% endfor %}

    <ul class="noJS">
    {% for cat in category.get_children|tree_info %}
    <li><a href="/categories/{{ cat.id }}/">{{  cat.name }}aa</a> </li> 

    {% endfor %}
    </ul>
{% endfor %}

this is the model

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    description = models.TextField(blank=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

    def __unicode__(self):
        return self.name

any idea?


Solution

  • This worked

    {% for category in categories %}
                    <li>
                    <a href="/categories/{{ category.id }}/">{{ category.name }}</a>  
                    <ul class="noJS">
                        {% for cat in category.get_children %}              
                        <li><a href="/categories/{{ cat.id }}/">{{  cat.name }}</a> </li> 
                        {% endfor %}
    
                    </ul>
                </li>
                    {% endfor %}