Need to convert a string to int in a django template

Solution 1:

you can coerce a str to an int using the add filter

{% for item in numItems|add:"0" %}

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#add

to coerce int to str just use slugify

{{ some_int|slugify }}

EDIT: that said, I agree with the others that normally you should do this in the view - use these tricks only when the alternatives are much worse.

Solution 2:

I like making a custom filter:

# templatetags/tag_library.py

from django import template

register = template.Library()

@register.filter()
def to_int(value):
    return int(value)

Usage:

{% load tag_library %}
{{ value|to_int }}

It is for cases where this cannot be easily done in view.