Django Templating in Class Based Views


Example

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

In your views.py:

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 %}
<ul>        
    <li>{{ item }}</li>
</ul>
{% endfor %}

You can also retrieve additional properties of the data.

Assuming your model Item has a name field:

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