Django Pluralize Outside of Templates
Photo by Sam Dan Truong on Unsplash
How to use the pluralize filter directly in python
The pluralize filter is great for humanizing text in templates. But what if you want to use the same function inside of your python code. For example, let's say you are sending back a message via ajax.
It is simple enough to make use of the same pluralize filter function in your python code:
1from django.template.defaultfilters import pluralize23def message(count):4 return '{} item{} {} updated.'.format( count, pluralize(count), pluralize(count, 'was,were'))
Testing this would produce the following results:
1In [3]: message(1) Out[3]: '1 item was updated.'23In [4]: message(2) Out[4]: '2 items were updated.'45In [5]: message(0) Out[5]: '0 items were updated.'