Django模板使用索引迭代模型字段

Django模板使用索引迭代模型字段,django,templates,Django,Templates,我有以下模型: class UserProfile(...): ... photo1 = models.URLField() photo2 = models.URLField() photo3 = models.URLField() photo4 = models.URLField() photo5 = models.URLField() 在创建/更新模板中,我必须为file1将以下div的五份副本写入file5: <div>

我有以下模型:

class UserProfile(...):
    ...
    photo1 = models.URLField()
    photo2 = models.URLField()
    photo3 = models.URLField()
    photo4 = models.URLField()
    photo5 = models.URLField()
在创建/更新模板中,我必须为
file1
将以下
div
的五份副本写入
file5

<div>  
  Photo 1:
  {% if userProfileForm.instance.file1 %}
    <a href="{{ userProfileForm.instance.file1 }}" target=_blank>View</a>
  {% endif %}
  <input type=file name=file1>
  {% if userProfileForm.instance.file1 %}
    <a href="{% url 'account:deletePhoto' userProfileForm.instance.id %}">Delete</a>
  {% endif %}
</div>

照片1:
{%if userProfileForm.instance.file1%}
{%endif%}
{%if userProfileForm.instance.file1%}
{%endif%}
是否有一种方法可以迭代字段
文件

{%i在'12345%}
照片{{forloop.counter}}:
...
{%endfor%}
在django中,您有。所以我认为,如果您使用get_fields方法(也许您会过滤掉所需的字段),这就解决了您的问题

希望能有帮助

使用示例更新

让我来说明你应该如何解决你的问题:

desired_fields = []
for field in UserProfile._meta.get_fields()
  if "photo" in field.name:
    desired_fields.append(field.name)
context.update(fields=desired_fields)  # pass it in the context
此时,您就有了所需的字段,这些字段应该与模板中的for循环一起使用。还有一件事,您需要添加一些模板标记,以从字符串表示中获取真实字段:

# custom template tag
def from_string_to_field(instance, field_str):
  return getattr(instance, field_str, None)
在模板中,代码如下所示

{% for field in fields %}
  {{userProfileForm.instance|from_string_to_field:"field"}}
{% endfor %}

可能有人帮助您创建一个拐杖来解决您的问题,但我认为最好的方法是使用
photo
sequence
fields创建相关模型,但如何在模板中获取字段<代码>{userProfileForm.instance.get_fields}}不起作用。请查看更新的答案,希望它能为您提供更多详细信息和使用_MetaAPI的完整路径。
{% for field in fields %}
  {{userProfileForm.instance|from_string_to_field:"field"}}
{% endfor %}