Django: reliably saving URLs to a file field

wrap them in django.core.files.File() objects - but File can't handle the file-like objects returned by urlopen (see http://code.djangoproject.com/ticket/8501) which don't implement all of the methods supported by a normal file.

Most of the suggestions you'll find online suggest using urllib.urlretrieve to save the remote URL to a temporary file which you can then wrap normally. Unfortunately, urlretrieve does no error handling by default and it's a bit contorted to add so I found it easier to use Django's NamedTemporaryFile class:
from django.core.files import File

from django.core.files.temp import NamedTemporaryFile



img_temp = NamedTemporaryFile(delete=True)

img_temp.write(urllib2.urlopen(url).read())

img_temp.flush()



im.file.save(img_filename, File(img_temp))

comments powered by Disqus