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

时间:2017-10-31 03:35:44

标签: django templates

我有以下型号:

class UserProfile(...):
    ...
    photo1 = models.URLField()
    photo2 = models.URLField()
    photo3 = models.URLField()
    photo4 = models.URLField()
    photo5 = models.URLField()

在创建/更新模板中,我必须为divfile1写下以下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>

有没有办法迭代字段file<i>

{% for i in '12345' %}
  <div>
    Photo {{ forloop.counter }}:

    ...

  </div>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

在django你有_meta API。所以我认为这可以解决你的问题,如果你使用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 %}
相关问题