I have a model Category which has a FK reference to itself. How can i send the data to a template and make it look like this
- Category 1
- List item
- List item
- Category 2
- List item
- List item
I have a model Category which has a FK reference to itself. How can i send the data to a template and make it look like this
Looks like you're trying to make recursion work in templates. This might help: http://www.undefinedfire.com/lab/recursion-django-templates/
You might be looking for something like this:
models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'categories'
ordering = ['name']
views.py
from myapp.models import Category # Change 'myapp' to your applications name.
from django.shortcuts import render_to_response
def category(request)
cat_list = Category.objects.select_related().filter(parent=None)
return render_to_response('template.html', { 'cat_list': cat_list })
template.html
<ul>
{% for cat in cat_list %}
<li>{{ cat.name }}</li>
<ul>
{% for item in cat.child.all %}
<li>{{ item.name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>