Django can not access all objects in a model

advertisements

My view looks like this:

class PageView(DetailView):
    queryset = Page.objects.all()
    template_name = 'page.html'
    def get_context_data(self, **kwargs):
        context = super(PageView, self).get_context_data(**kwargs)
        context['category'] = Category.objects.all()
        context['categoryitem'] = CategoryItem.objects.all()
        return context

When in template I try to execute the given context variables like so {{ category }} it prints out [<Category: Something not so interesting>] aka model name + it's title, I presume the title gets printed out because I've set __unicode__(self): return self.title in the model.py, but I cannot access any other fields from the given object. category.id is blank as so is everything else. How can I access those?


Your code is:

context['category'] = Category.objects.all()

So it should be:

context['categories'] = Category.objects.all()

And in your template:

{% for category in categories %}
  {{ category.name }}
{% endfor %}

The output you got in your test makes sense:

[<Category: Something not so interesting>]

it's an array with only one entry, this entry is an object of the class Category, and the string representation of it is "Something not ..."