views:

24

answers:

1

I have this class

class Category(models.Model):
    title = models.CharField(max_length=60)
    created = models.DateTimeField()

def __unicode__(self):
    return self.title

class Meta:
    verbose_name_plural = "Categories"

I can access its items using Category.objects.all() from my views.py. I want to access these items inside my template, but obviously this doesn't work:

{% for category in Category.objects.all() %}
    {{ category }}
{% endfor %}

How can I solve the issue with getting the items in a template?

+2  A: 

I strongly suggest explicitly passing in Category.objects.all() from the view. This will let you reuse the template irrespective of how you filter your categories.

def my_view(request, *args, **kwargs):
    all_categories = Category.objects.all()
    ...

{% for category in all_categories %}

If you are reluctant to do this then pass Category as a template variable and then lose the () at the end of all:

def my_view(request, *args, **kwargs):
    model_variable = Category
    ...

{% for category in model_variable.objects.all %}
Manoj Govindan
Calling `Category.objects.all()` from within the view makes more sense, especially when you think that if you have many objects returned you'll eg. need a pagination which you have to generate in the view as well!
lazerscience
While I agree it makes more sense to call from within the view, I actually prefer to do all my pagination in the template, using django-pagination (http://code.google.com/p/django-pagination/)
Jordan Reiter