3

I have used easy_thumbnailsto store images in my application. I have a model name Profile that has picture field which is ThumbnailerImageField. In my code I am fetching image using a url I have using the follwing code

f = urllib.request.urlretrieve(picture_url)

Now, f[0] is a string containing path to file in /tmp/ directory. I want to save this image to my picture field. So, I used following code

profile.picture.save(os.path.basename(picture), File(open(f[0])))

But the problem is that the saved file is corrupted for some reason and I am unable to open it. Whereas when I check for the file in/tmp/, it is a proper image file. Can anyone point out what am I doing wrong here?

EDIT:

My field definition is as following picture = ThumbnailerImageField(upload_to=name, max_length=3072)

and name is as following

def name(inst, fname):
f = sha256((fname + str(timezone.now())).encode('utf-8')).hexdigest()
f += fname
return '/'.join([inst.__class__.__name__, f])
Rajesh Yogeshwar
  • 2,111
  • 2
  • 18
  • 37

1 Answers1

3
from django.core.files.temp import NamedTemporaryFile
try:
    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(
        urllib2.urlopen(picture_url).read()
    )
    img_temp.flush()
    profile.picture.save('picture.jpg', File(img_temp))
    profile.save()
except:
    pass
zlovelady
  • 4,037
  • 4
  • 32
  • 33
praveen
  • 105
  • 2
  • 8