Django Templating in Class Based Views


You can pass data to a template in a custom variable.

In your

from django.views.generic import TemplateView
from MyProject.myapp.models import Item

class ItemView(TemplateView):
    template_name = "item.html"

    def items(self):
        """ Get all Items """
        return Item.objects.all()

    def certain_items(self):
        """ Get certain Items """
        return Item.objects.filter(model_field="certain")
    def categories(self):
        """ Get categories related to this Item """
        return Item.objects.get(slug=self.kwargs['slug']).categories.all()

A simple list in your item.html:

{% for item in view.items %}
    <li>{{ item }}</li>
{% endfor %}

You can also retrieve additional properties of the data.

Assuming your model Item has a name field:

{% for item in view.certain_items %}
    <li>{{ }}</li>
{% endfor %}