【发布时间】:2022-01-05 00:59:36
【问题描述】:
<here all loading of static , template_filters, crispy_forms >
<form>
{% for i in artifact_length %}
{% with artifact_name="artifact"|artifact_name:forloop.counter0 %}
{{form.artifact_name|as_crispy_field}}
{% endwith %}
{%endfor%}
</form>
这是相关的模板代码。在这里,我想将名称为 artifact_0、artifact_1 的表单字段呈现为来自表单。 with 内的变量 artifact_name 工作正常并返回预期的标识符 artifact_0 ,artifact_1,但我想将这些变量用作表单字段以呈现为 as_crispy_field。
代码{{form.artifact_name|as_crispy_field}} 不打印任何内容,因为它假定表单为名称为artifact_name 的字段,但事实并非如此。相反,我想在这里使用变量的值。
forms.py
class Someform(forms.form):
def __init__(self, artifact_obj):
super().__init__()
count = 0
for artifact in artifact_obj:
self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
count += 1
tags.py
@register.filter('artifact_name')
def get_artifact_name(artifact_prefix: str, counter: int):
print('method', 'prefix', artifact_prefix, 'counter', counter)
return f'{artifact_prefix}_{counter}'
正在创建可变长度表单。如 informs.py 表单字段是使用 artifact_count 创建的,其中 count 的范围可以从 0 到 obj 的 len。
【问题讨论】:
-
这些是您表单中唯一的字段吗?
len(artifact_obj)是否与artifact_length相同? -
还有更多字段,我可以按名称对它们进行排序。但这些都是可变字段,无法估计会有多少。需要循环迭代。 .是的,artifact_length 与 artifact_obj 相同。
-
它在上下文中被传递为
{'artifact_length':range(len(artifact_obj))} -
其他字段的渲染顺序如何?
-
顺序无关紧要,我只是将它们呈现在所有这些变量字段之上。现在也需要渲染这些字段
标签: django django-views django-forms django-templates django-template-filters