【问题标题】:I have an error in django template for loop我在循环的 django 模板中有一个错误
【发布时间】:2023-01-19 16:18:08
【问题描述】:
I have an error in django template for loop.    
My code: 
     <div class="form-group col-md-4 form-field">
                                        <label>Year</label>
                                        <select name="year" id="year" name="year">
                                            {% for y in range(1980, (datetime.datetime.now().year + 1)) %}
                                                <option value="{{ y }}">{{ y }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
    
    My error:
    'for' statements should use the format 'for x in y': for x in y range(1980, (datetime.datetime.now().year + 1))
    
    Please help me to resolve this issue.

请帮我解决这个问题。 请帮我解决这个问题。

【问题讨论】:

  • 给出的错误消息似乎很明确。您是否尝试过更改代码以遵循该格式?

标签: html css django django-rest-framework jinja2


【解决方案1】:

您不能在模板中使用标准 Python 逻辑。

阅读关于该主题的DOCS

最简单的方法似乎是创建自定义模板标签过滤器:

import datetime
from django import template

register = template.Library()

@register.filter
def get_year_range(starting_year):
    return range(int(starting_year), (datetime.datetime.now().year + 1))

并在模板中使用它:

{% load custom_tags %}

...
{% for y in "1980"|get_year_range %}
    <option value="{{ y }}">{{ y }}</option>
{% endfor %}

MORE ABOUT TEMPLATE TAGS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2023-03-09
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多