Django’s built-in template tags are simply Python functions which means they can be used in places other than templates such as class-based views.
Here’s an example using pluralize:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.views.generic import ListView | |
from django.template.defaultfilters import pluralize | |
from myapp.models.Product | |
class MyView(ListView): | |
queryset = Product.objects.all() | |
template_name = 'product.html' | |
context_object_name = 'products' | |
def get_context_data(self, **kwargs): | |
context = super(MyView, self).get_context_data(**kwargs) | |
context['title'] = len(context['products']) + ' Product' + pluralize(context['products']) + ' Found' | |
return context |