You cannot use the range()
function in the template. Rather do the following.
In your view.py add the following:
def index(request):
files = listdir("/path/to/directory/")
filelen = len(files)
return render(request, 'path/to/template.html', {'filelen': filelen})
and then in your template loop using that range number as follows:
{%for i in filelen %}
...
{% endfor %}
So I am trying to get Django to display a template that shows a list of files on a local directory. My views.py looks like this:
from django.shortcuts import render
from django.http import HttpResponse
from os import listdir
def index(request):
files = listdir("/path/to/directory/")
filelen = len(files)
return render(request, 'path/to/template.html')
My html template looks like this:
{%for i in range(1, filelen)%}
<tr>
<td>{{i}}</td>
<td>{{files[i]}}</td>
{% if "a" in files[i] %}
<td>✓</td>
{% else %}
<td>x</td>
{% endif %}
{% if "b" in files[i] %}
<td>✓</td>
{% else %}
<td>x</td>
{% endif %}
But when I try to run it I get the following error:
Error at line 39
'for' statements should use the format 'for x in y': for i in range(1, len_files)
Anybody know how to get this to work? I have tried replacing filelen with {{filelen}} but that gave me the same error.
If the answer helped you, please mark it as answered.