I have a dictionary with lists as values (truncated to give you an example):
imageFiles:
for prop in context['results'][0]:
imageFolderPath ='./media/uploaded/prop_images/' + prop.property_ID
if os.path.isdir(imageFolderPath):
imageFileList[prop.property_ID] = [f for f in listdir(imageFolderPath) if isfile(join(imageFolderPath, f))]
context['imageFiles'] = [imageFileList]
Here is what shows up when I print it directly in the template:
[{'R01': ['02secparking27.jpg', '10-2017-ff-detail-1200x627.jpg', '1200x820.jpg', '12539233_web1_180704-VMS-parking-lot.jpg', '16.12.01-519196006.jpg',],
'R02': ['asdasd.jpg','12131asad.jpg','asdasdasd.jpg']}]
In the template, I am trying to access the image names by iterating but I am getting no values.
{% for keys,values in imageFiles %}
{% for x in values %}
<p> {{X}} </p>
{% endfor %}
{% endfor %}
getting error
"Need 2 values to unpack in for loop; got 9."
I also tried imageFiles.items as suggested in other posts and it doesn't seem to work.
What am I doing wrong? Wracking my brain here.
So, you're passing in:
context['imageFiles'] = [imageFileList]
Which is pretty confusing, for no good reason. What you're calling imageFileList
isn't a list, but a dictionary. Then, what you pass into the template is a list with a single element, namely that dictionary.
Fix: Pass in the dictionary (it would be even nicer if you changed the name of imageFileList
to something less confusing):
context['imageFiles'] = imageFileList
In your template:
{% for key, value in imageFiles.items %}
{% for x in values %}
<p> {{x}} </p>
{% endfor %}
{% endfor %}
Assumed
dct = your input dictionary
code:
[value for keys, values in dct.items() for value in values]
will give you the below list of file names:
['02secparking27.jpg',
'10-2017-ff-detail-1200x627.jpg',
'1200x820.jpg',
'12539233_web1_180704-VMS-parking-lot.jpg',
'16.12.01-519196006.jpg',
'asdasd.jpg',
'12131asad.jpg',
'asdasdasd.jpg']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.