Randy Tang
Randy Tang

Reputation: 4353

Django templates iterate model fields with indices

I have the follow model:

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

And in the Create/Update template, I have to write five copies of the following div for file1 to 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>

Is there a way to iterate field file<i>?

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

    ...

  </div>
{% endfor %}

Upvotes: 0

Views: 208

Answers (1)

Giorgi Jambazishvili
Giorgi Jambazishvili

Reputation: 743

in django you have _meta API. So I think this solves your problem if you use get_fields method (and maybe you will filter desired fields out).

hope it helps.

update with example

let me show how you should solve your problem:

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

at this point you have your desired fields which should be used with for loop in the template. And one more thing, you would need to add some template tag to get real field from string representation:

# custom template tag
def from_string_to_field(instance, field_str):
  return getattr(instance, field_str, None)

and in the template code will look like this

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

Upvotes: 1

Related Questions