I have setup a django-treebeard model that has child nodes and what not. How do I now display this in my template? This is what I have so far.
My Models:
class SiteMapEntry(MP_Node):
name = models.CharField(max_length=100, null=False, blank=False)
url = models.CharField(max_length=1000, null=False, blank=False)
node_order_by = ['name']
class Meta:
verbose_name = "Sitemap Entry"
verbose_name_plural = "Sitemap Entries"
def __unicode__(self):
return ('%s - %s' % (self.name, self.url))
My Views:
from django.views.generic import ListView
class SiteMap(ListView):
model = SiteMapEntry
template_name = 'sitemaps.html'
My Template:
{% block content %}
<h1>Sitemap</h1>
<br /><br />
{% for url in object_list %}
<p>{{ url.name }}</p>
<p>{{ url.url }}</p>
{% endfor %}
{% endblock content %}
What this is doing right now, obviously is just listing the nodes and its children without any indenting. How do I list it like a tree in my template?
You can use the get_annotated_list
node method to get a data structure you can iterate on in the template:
http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.get_annotated_list
There's also an example there that shows you exactly how to do it:
{% for item, info in annotated_list %}
{% if info.open %}
<ul><li>
{% else %}
</li><li>
{% endif %}
{{ item }}
{% for close in info.close %}
</li></ul>
{% endfor %}
{% endfor %}
Have a look at the dump_bulk
method which returns a nested data structure too:
http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.dump_bulk
Hope it's helpful.