简体   繁体   English

jinja 中从 str 到 int 的类型转换

[英]Typecasting from str to int inside jinja

I encountered a scenario where I need to fetch numeric data from the database and run that number of loops on my template, something like:我遇到了一个场景,我需要从数据库中获取numeric数据并在我的模板上运行该数量的循环,例如:

in my views.py :在我的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)

my template :我的template

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

Now it says following error :现在它说以下error

'str' object cannot be interpreted as an integer

So, I try to typecast the noNumeric into int like this:因此,我尝试将noNumeric类型转换为int ,如下所示:

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

This time it gives following error:这次它给出了以下错误:

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

How can I fix this issues?我该如何解决这个问题?

I just found a solution, like:我刚刚找到了一个解决方案,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM