开发者

What is the best way to get row_num in django?

What is the best way to get row_num in django ? Can we use a variable as 开发者_运维技巧counter in django template tags ?

{% for o in objects %}
<tr>
  <td>{{ row_num }}</td>
  <td>{{ o.first_name }}</td>
  <td>{{ o.last_name }}</td>
</tr>
{% endfor %}

Thanks in advance.


You can use the forloop template tag :

  • forloop.counter -> The current iteration of the loop (1-indexed)
  • forloop.counter0 -> The current iteration of the loop (0-indexed)
  • forloop.revcounter -> The number of iterations from the end of the loop (1-indexed)
  • forloop.revcounter0 -> The number of iterations from the end of the loop (0-indexed)
  • forloop.first -> True if this is the first time through the loop
  • forloop.last -> True if this is the last time through the loop
  • forloop.parentloop -> For nested loops, this is the loop "above" the current one


I'm not using django (I'm using pylons) but I dont think that this is actually a django "problem". You should use "enumerate". It is part of the python language.

Like this:

for i, book in enumerate(books): 
    print i+". "+book.name 

this would print

  1. Harry Potter
  2. Lord of the Rings

so in your case you should write:

{% for i, o in enumerate(objects) %}
<tr>
  <td>{{ i }}</td>
  <td>{{ o.first_name }}</td>
  <td>{{ o.last_name }}</td>
</tr>
{% endfor %}

I hope this was what you were looking for.

Best, k.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜