Skip to content

Instantly share code, notes, and snippets.

@mebusw
Created July 25, 2014 01:52
Show Gist options
  • Save mebusw/6bfef02bfdeb7c071080 to your computer and use it in GitHub Desktop.
Save mebusw/6bfef02bfdeb7c071080 to your computer and use it in GitHub Desktop.
Programmatically saving image to Django ImageField
################# Solution1 ##############
# First, copy your image file to the upload path (assumed = 'path/' in following snippet).
#
# Second, use something like:
class Layout(models.Model):
image = models.ImageField('img', upload_to='path/')
layout = Layout()
layout.image = "path/image.png"
layout.save()
################# Solution2 ##############
class CachedImage(models.Model):
url = models.CharField(max_length=255, unique=True)
photo = models.ImageField(upload_to=photo_path, blank=True)
def cache(self):
"""Store image locally if we have a URL"""
if self.url and not self.photo:
result = urllib.urlretrieve(self.url)
self.photo.save(
os.path.basename(self.url),
File(open(result[0], 'rb'))
)
self.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment