I'm trying to retrieve a list of images in a directory, and store this list into a attribute of a class. But when i try to get the list from the object it appears empty.This is the class:
class Hunting(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=500)
images = {}
def __str__(self):
res = ''
for image in self.images:
res = res+image
return res
def __unicode__(self):
return self.id
And then this is what i do to populate and read the list:
page = int(page)
huntings = Paginator(Hunting.objects.all(), 9)
images = {}
for hunting in huntings.page(page):
dir_name = settings.IMAGES_ROOT+'\\theme1\\images\\cotos\\'+str(hunting.id)+'\\' # insert the path to your directory
path = os.path.join(settings.STATIC_URL, dir_name)
print >>sys.stderr, '--PATH:' + path
if os.path.exists(path):
print >>sys.stderr, '--LIST IMAGE HUNTING '+str(hunting.id)+'--'
img_list = os.listdir(path)
hunting.images=img_list
print >>sys.stderr, hunting.images
for hunting in huntings.page(page):
print >>sys.stderr, '*******hunting '+str(hunting.id)+':'
print >>sys.stderr, hunting.images
So, when i am iterating the first time and printing the hunting.images list i got:
--LIST IMAGE HUNTING 2--
['1_tn.jpg', '2_tn.jpg', '3_tn.jpg', '4_tn.jpg']
--LIST IMAGE HUNTING 4--
['coto10.png', 'coto11.png', 'coto12.png']
But the second iteration, trying to get the list i stored before i get an empty list
*******hunting 2:
{}
*******hunting 4:
{}
I think what happened is that you call huntings.page(page)
for both of the loops. The first loop you did assign the images to the result of huntings.page(page)
, but then you didn't keep the result, so for the second loop you call huntings.page(page)
again and you got the same initial result as before.
I'm not sure what you want to achieve here, but you need to get the return value first in a variable then update it:
# keep the return value in variable huntings
huntings = [for hunting in huntings.page(page)]
for hunting in huntings:
# do your hunting.images = img_list
for hunting in huntings:
print >>sys.stderr, hunting.images
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.