【问题标题】:Typecasting from str to int inside jinjajinja 中从 str 到 int 的类型转换
【发布时间】:2021-04-15 03:20:01
【问题描述】:

我遇到了一个场景,我需要从数据库中获取 numeric 数据并在我的模板上运行该数量的循环,例如:

在我的views.py:

from django.template.defaulttags import register

@register.filter
def get_range(value):
    return range(value)

def quesSetting(request):
    questionSet_obj = questionSet.objects.filter(id = pk).first()
    quesSetting_dict = {
        'noNumeric' : questionSet_obj.noNumeric,
    }
    return render(request, 'app/quesSetting.html', quesSetting_dict)

我的template:

{% for i in noNumeric|get_range %}
  <input type="text" class="form-control" name="numericQuestion" array_column="{{ i }}">
{% endfor %}

现在它说关注error

'str' object cannot be interpreted as an integer

所以,我尝试将noNumeric 转换为int,如下所示:

{% for i in int(noNumeric)|get_range %}
  <input type="text" class="form-control" name="numericQuestion" array_column="{{ i }}">
{% endfor %}

这次它给出了以下错误:

Could not parse some characters: int|(noNumeric)||get_range

我该如何解决这个问题?

【问题讨论】:

  • noNumeric btw 的示例输出是什么?
  • int 值,在我的测试用例中是:2
  • 并确认您的自定义 |get_range 是否正常工作?
  • 是的,为了确认,我已将 noNumeric 替换为 2,它工作正常

标签: python django jinja2


【解决方案1】:

我刚刚找到了一个解决方案,比如:

@register.filter
def get_range(value):
    value = int(value)
    return range(value)

【讨论】:

  • 同时,我已经测试了你之前的get_range 函数,它运行良好。 imo,为什么它转换为字符串值。
  • 我很困惑。据我所知,该方法也应该可以完美运行。无论如何,感谢@binpy 的帮助!
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多