Walucas
Walucas

Reputation: 2568

Could not parse the remainder in django {% for clause

Inside an HTML I am trying to perform a double for, which the second one inherits data from the father, as follow:

{% for category in categories %}
            <li><a href="/categories/{{ category.id }}/">{{ category.name }}</a>
            {% for cat in category.objects.filter(parent=category.id) %}
                {% if forloop.first %} 
                <ul class="noJS">
                {% endif %}
                    <li><a href="/categories/{{ cat.id }}">{{cat.name}}</a></li> 
                </ul>
            {% endfor %}

            {% endfor %} 

The problem is that I am getting error:

TemplateSyntaxError at /
Could not parse the remainder: '(parent=category.id))' from 'ca

tegory.objects.filter(parent=category.id))'
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.4.3
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '(parent=category.id))' from 'category.objects.filter(parent=category.id))'

Any idea?

Upvotes: 2

Views: 3441

Answers (3)

Walucas
Walucas

Reputation: 2568

I am using MPTT so I just call a method for children nodes:

        {% for cat in category.get_children %}

that is available from MPTT

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

Because you have a relationship, even a self-referential one, you get an accessor for the reverse relation. If you haven't set related_name, that will just be category_set. So you can just do:

{% for cat in category.category_set.all %}

Upvotes: 0

catherine
catherine

Reputation: 22808

Idea:

models.py

class Category(models.Model):
    .........

    def data(self):
        return Category.objects.filter(id=self.id)

template

{% for category in categories %}
<li><a href="/categories/{{ category.id }}/">{{ category.name }}</a>
    {% for cat in category.data %}
        {% if forloop.first %} 
        <ul class="noJS">
        {% endif %}
            <li><a href="/categories/{{ cat.id }}">{{cat.name}}</a></li> 
        </ul>
    {% endfor %}
{% endfor %} 

Upvotes: 1

Related Questions