需要在django模板中将字符串转换为int

use*_*808 43 django django-templates


我试图将url参数传递给像这样的django模板......

response = render_to_string('persistConTemplate.html', request.GET)
Run Code Online (Sandbox Code Playgroud)

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

在模板中我尝试使用这样的参数之一......

{% for item in (numItems) %}

  item {{item}}

{% endfor %}
Run Code Online (Sandbox Code Playgroud)

numItems是我在我的请求中发送的url参数之一,就像这样......

http:/someDomain/persistentConTest.html/?numItems=12
Run Code Online (Sandbox Code Playgroud)

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

图像1图像2

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

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

谁能告诉我我错了什么?

scy*_*ale 113

你可以使用add过滤器将str强制转换为int

{% for item in numItems|add:"0" %}
Run Code Online (Sandbox Code Playgroud)

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

强迫int只使用slugify

{{ some_int|slugify }}
Run Code Online (Sandbox Code Playgroud)

编辑:那说,我同意其他人通常你应该在视图中这样做 - 只有当替代品更糟糕时才使用这些技巧.


cli*_*ime 20

我喜欢制作自定义过滤器:

# templatetags/tag_library.py

from django import template

register = template.Library()

@register.filter()
def to_int(value):
    return int(value)
Run Code Online (Sandbox Code Playgroud)

用法:

{% load tag_library %}
{{ value|to_int }}
Run Code Online (Sandbox Code Playgroud)

这是为了在视野中无法轻易完成的情况.

  • 这比另一个更清楚. (4认同)

Yuj*_*ita 10

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

我觉得上面的例子不起作用 - 你不能迭代一个整数.

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 %}
Run Code Online (Sandbox Code Playgroud)


小智 10

最简单的方法是使用内置的floatformat过滤器。

对于整数

{{ value|floatformat:"0" }}
Run Code Online (Sandbox Code Playgroud)

对于精度为 2 的浮点值

{{ value|floatformat:"2" }}
Run Code Online (Sandbox Code Playgroud)

它也将四舍五入到最接近的值。有关更多详细信息,您可以查看https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#floatformat