Need to convert a string to int in a django template

user479808 picture user479808 · Jan 28, 2011 · Viewed 75.1k times · Source


I am trying to pass in url parameters to a django template like this...

response = render_to_string('persistConTemplate.html', request.GET)

This the calling line from my views.py file. persistConTemplate.html is the name of my template and request.GET is the dictionary that contains the url parameters.

In the template I try to use one of the parameters like this...

{% for item in (numItems) %}

  item {{item}}

{% endfor %}

numItems is one of the url parameters that I am sending in my request like this...

http:/someDomain/persistentConTest.html/?numItems=12

When I try the for loop above, I get an output like this....

image 1 image 2

I am expecting and would like to see the word image printed 12 times...

image 1 image 2 image 3 image 4 image 5 image 6 image 7 image 8 image 9 image 10 image 11 image 12

Can anyone please tell me what I am going wrong?

Answer

scytale picture scytale · Sep 13, 2011

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.