Created
July 25, 2014 01:52
-
-
Save mebusw/6bfef02bfdeb7c071080 to your computer and use it in GitHub Desktop.
Programmatically saving image to Django ImageField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################# 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