0

I want to use a Django forloop.counter like this:

{% for i in "xxxxxxxxxxxxxxxxxxxx" %}
    {{ i.time_code{{forloop.counter}} }}
{% endfor %}

Turns out, it's not possible to do that.

Reason to accomplish this. I have 20 database coloumns like: time_code1, time_code2 ....time_code20. So, instead of calling each separately I want to do this.

pynovice
  • 7,424
  • 25
  • 69
  • 109

2 Answers2

0

I've used at in a similar way. Here is the example, don't know if it will help.

<form action= "{% url 'result_show' forloop.counter0 %}" method="post">

What it does is accepts the output of forloop.counter0 as a parameter of a method in view. And it works that way.

Have you considered migrating the time_codes to a list and than accessing them via forloop.counter?

TheMeaningfulEngineer
  • 15,679
  • 27
  • 85
  • 143
0

I'm not sure whether I understand your question correctly. Do you want to retrieve attributes dynamically? You could write a custom tag:

from django.template import Library

register = Library()

@register.simple_tag
def get_attr(obj, name, default=None):
    return getattr(obj, str(name), default)

then you can pass the list of attributes to your template:

attrs = ( "time_code"+str(i) for i in xrange(0, 100) )
return render_to_response("test.html", { "attrs": attrs })

and finally in your template:

{% for attr in attrs %}
    {% get_attr i attr %}
{% endfor %}
freakish
  • 54,167
  • 9
  • 132
  • 169