2013-05-05 53 views
14

連接我在models.py的Django從URL保存圖像和ImageField的

class Item(models.Model): 
    image_file = models.ImageField(upload_to='images') 
    image_url = models.URLField() 

我想自動Django的本地下載和保存圖像從image_urlimage_file

「連接」它應該如何行爲:

  1. 我粘貼https://docs.djangoproject.com/s/img/site/hdr_logo.gifimage_url管理中的字段
  2. 單擊「保存」
  3. 在模板中寫入<img src="{{ item.image_file.url }}">。這表明從我的服務器 圖像,不djangoproject.com

我已經試過:

我已經覆蓋Item類的save方法。我通過urllib本地保存的圖像,但我被困在這個保存的圖像與image_file

回答

32
from django.core.files import File 
import os 

class Item(models.Model): 
    image_file = models.ImageField(upload_to='images') 
    image_url = models.URLField() 

... 

def get_remote_image(self): 
    if self.image_url and not self.image_file: 
     result = urllib.urlretrieve(self.image_url) 
     self.image_file.save(
       os.path.basename(self.image_url), 
       File(open(result[0])) 
       ) 
     self.save() 

您可以覆蓋默認的保存()方法連接到自動調用get_remote_image()。

參見:https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

+0

你如何設置圖像的文件名? – User 2016-12-09 22:56:34

+2

Python3更新:http://stackoverflow.com/questions/17960942/attributeerror-module-object-has-no-attribute-urlretrieve – 43Tesseracts 2017-01-07 06:17:41

0

對於python3

from django.core.files import File 
from urllib import request 
import os 

class Item(models.Model): 
    image_file = models.ImageField(upload_to='images') 
    image_url = models.URLField() 

... 

def get_remote_image(self): 
    if self.image_url and not self.image_file: 
     result = request.urlretrieve(self.image_url) 
     self.image_file.save(
       os.path.basename(self.image_url), 
       File(open(result[0])) 
       ) 
     self.save() 

從這裏:http://stackoverflow.com/questions/17960942/attributeerror-module-object-has-no-attribute-urlretrieve

相關問題