Hello,

this is   probably a total newbie question, but I am really stumped on
how to do this best. Coming from a PHP background I tried to loop
through all categories and make a nested list. I kept on getting
errors. Since django is so powerful there had to be a way to do this
in the model itself. What I am trying to do is print a list of
categories and if they have a sub category to print that list.

Basically a nested list like:
Main Category A
Main Category B
--Sub Category A
--Sub Category B
Main Category C
...

The code below prints out a list of all categories which are not sub
categories. But I can't seem to find a way to incorporate the sub
categories. I already thought about iterating through the sub
categories (in the template) but there are some categories which do
not have sub categories, so the filtering of the categories wouldn't
have worked.

Is the only way to make a separate table (model class) for the sub
categories?

I am quite stumped. Can anyone give me some tips?
Thanks
Casper




# models.py
...
class CategoryManager(models.Manager):
        def main(self):
                return self.filter(subcategory_of__isnull=True)


class Category(models.Model):
        name = models.CharField(max_length=50)
        subcategory_of = models.ForeignKey('self', blank=True, null=True)

        def __uniode__(self):
                return self.name

        objects = CategoryManager()
...

# views.py
...
def index(request):
        t=Category.objects.main()
        return render_to_response('categories.html', {'cats': t,},)
...

# categories.html
...
{% if cats %}
    <ul>
    {% for cat in cats%}
        <li>{{cat}}</li>
    {% endfor %}
    </ul>

{% else %}
    <p>No categories available.</p>
{% endif %}
...


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to