21

this is my code :

{% for i in range(7)%}
        <option value={{i+1}}> {{i+1}}</option>
{% endfor %}

but it show error ,

what can i do ,

thanks

zjm1126
  • 34,604
  • 53
  • 121
  • 166
  • http://stackoverflow.com/questions/1107737/numeric-for-loop-in-django-templates same question? – dting Mar 09 '11 at 08:09

3 Answers3

55

In python strings are iterables so this works :

{% for i in "1234567" %}
    <option value={{i}}> {{i}}</option>
{% endfor %}

It's explicit, so quite OK, but zjm1126's answer is probably better for long term consideration.

blobmaster
  • 853
  • 8
  • 11
50

views.py:

context['loop_times'] = range(1, 8)

html:

{% for i in loop_times %}
        <option value={{ i }}>{{ i }}</option>
{% endfor %}
ghickman
  • 5,893
  • 9
  • 42
  • 51
zjm1126
  • 34,604
  • 53
  • 121
  • 166
  • 12
    +1: Best to put this in the view, but `range(1, 8)` would be much cleaner. – Sam Dolan Mar 09 '11 at 09:28
  • 2
    Why not just pass the range? view: context['loop_range'] = range(1, 8) template: {% for i in loop_range %} ... {% endfor %} – Mouad Debbar Jan 08 '14 at 08:17
  • Love the simplicity, thank you. Bizarre that something so simple isn't supported in templates. – Alveoli Jul 31 '14 at 16:23
  • My question is, how do I add this getting for example user posts? I need to loop only three posts from users so how would I add the range within the view? For example ``` posts = Post.objects.all()```. Then in templates ```{% post in posts:"3" %}```. That is my approach but for my limited understanding I am not finding a clear answer. – Elias Prado Mar 14 '20 at 01:56
0

Django templates don't support ranges. You have a couple options:

  1. Add a range filter: http://djangosnippets.org/snippets/1357/

Here's how you add custom filters: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

  1. Use a different templating system, like Mako, that does support it.

http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language Django-Mako is a shortcut project for using Mako: http://code.google.com/p/django-mako/

Jordan
  • 31,971
  • 6
  • 56
  • 67