需要在 django 模板中将字符串转换为 int [英] Need to convert a string to int in a django template

查看:394
本文介绍了需要在 django 模板中将字符串转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试将 url 参数传递给这样的 django 模板...


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

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

这是来自我的 views.py 文件的调用行.persistConTemplate.html 是我的模板的名称,request.GET 是包含 url 参数的字典.

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 是我在这样的请求中发送的 url 参数之一......

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

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

当我尝试上面的 for 循环时,我得到这样的输出......

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

图片 1 图片 2

我期待并希望看到文字图像打印 12 次...

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

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

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?

推荐答案

是的,这个地方就是在视图中.

Yes, the place for this is in the view.

我觉得上面的例子行不通——你不能迭代一个整数.

I feel like the above example won't work -- you can't iterate over an integer.

numItems = request.GET.get('numItems')

if numItems:
   numItems = range(1, int(numItems)+1)

return direct_to_template(request, "mytemplate.html", {'numItems': numItems})


{% for item in numItems %}
 {{ item }}
{% endfor %}

这篇关于需要在 django 模板中将字符串转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆