Trees in Django

34 views
Skip to first unread message

Cody Scott

unread,
May 17, 2013, 10:28:12 AM5/17/13
to django...@googlegroups.com
I am categorizing models in a tree. The tree is created based on a string of where the model falls in the tree. The tree will not change once it is created.

I tried using django-mptt with this code to create the tree.

def add_new_nodes(category_string):
    for category in category_string.split(','):
        try:
            root = Category.get_root()
        except:
            root = Category.objects.create(value='')
        current_node = root
        for step in category.split(':'):
            added = False
            for node in current_node.get_children().all():
                print node.value
                print step
                if node.value == step:
                    added = True
                    current_node = node
                    break
            if not added:
                new_node = Category.objects.create(value=step, parent=current_node)
                current_node = new_node

But it each time is creating a new branch from the root even with two children of the root with the same name.

Or at least that is what I get from

{% load mptt_tags %}
<ul>
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>


So I am trying to use django-treebeard similarly but I am getting an error. 'str' object has no attribute 'META'

def tree(request):
    try:
        root = Category1.get_root_nodes()[0]
    except:
        root = Category1.add_root(value='')
    annotated_list = root.get_annotated_list()
    print annotated_list
    return render("tree.html", {'annotated_list':annotated_list})

{% 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 %}

But I get the error 'str' object has no attribute 'META'


Artem Zinoviev

unread,
May 18, 2013, 12:30:37 PM5/18/13
to django...@googlegroups.com
first parameter of render() function must be request...
try do it like this: 
*
   return render(request, "tree.html", {'annotated_list':annotated_list})
*
пятница, 17 мая 2013 г., 17:28:12 UTC+3 пользователь Cody Scott написал:
Reply all
Reply to author
Forward
0 new messages