0

i am new to django and tried to use the variable of an loop as a key for another object:

this is my views.py

...
files = Files.objects.filter(dataset__id = instance.dataset.id)
context = {'files': files, 'range': range(files.count())}
return render_to_response("test.html", context, context_instance=RequestContext(request))

and my test.html looks like this:

{% for i in range %}
<img title="{{i}}" src="{{files.i.data_files.url}}"/>
{% endfor %}

if i use files.0.data_files.url (or 1,2,3..) instead of files.i. it works, but i want to give out all images and also need the position of the image.

can you help me please?

1 Answer 1

1

the thing you're probably looking for is a magic variable {{ forloop.counter }} (or {{ forloop.counter0 }} if you want to use zero-based index) available inside {% for %} loop:

{% for file in files %}
   <img title="{{ forloop.counter }}" src="{{file.data_files.url}}"/>
{% endfor %}
Sign up to request clarification or add additional context in comments.

5 Comments

if i use this, could it be possible that the counter is on e.g. 3 but it takes the 6th file?
tbh: I didnt fully understand your question, but maybe if you can add your models into the question I could get the idea what are you trying to achieve.
i mean i have an file object like files = {0:{...}, 1:{..}, ...} and wanted to know, if the loop is always sorted or could it possible that that an object from the end is called first in the loop? in this case the counter and the index wouldnt be the same
and also if i set files = {2:{..}, 0:{..}, 1:{..}, ..}, would it then also agree with the counter?
The code you wrote in your last two comments looks like files is a dictionary, but I can see in your views.py that it's a QuerySet (which is basically a list). So... you didnt explain it, you make it even more confusing. Just put your models.py into your question pls!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.