我有一些代码可以从网络上获取图像并将其存储在模型中。重要的位是:
from django.core.files import File # you need this somewhereimport urllib# The following actually resides in a method of my modelresult = urllib.urlretrieve(image_url) # image_url is a URL to an image# self.photo is the ImageFieldself.photo.save( os.path.basename(self.url), File(open(result[0], 'rb')) )self.save()
这有点令人困惑,因为它脱离了我的模型并且脱离了上下文,但是重要的部分是:
- 从Web提取的图像未存储在upload_to文件夹中,而是由urllib.urlretrieve()作为临时文件存储,之后被丢弃。
- ImageField.save()方法采用文件名(os.path.basename位)和django.core.files.File对象。
让我知道你是否有疑问或需要澄清。
编辑:为清楚起见,这里是模型(减去任何必需的import语句):
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()



