【发布时间】:2013-11-18 10:56:33
【问题描述】:
我正在尝试根据this question 的答案从url 提交图像,但结果我成功存储了图像文件,但文件名.jpg 而不是image-name.jpg
代码
import urllib2
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from myapp.models import Mymodel
# Mymodel contain ImageField named image
extract_url = 'http://example.com/image-name.jpg'
my_temp = Mymodel()
image_name = extract_url.split('/')[-1]
image_temp = NamedTemporaryFile(delete=True)
image_temp.write(urllib2.urlopen(extract_url).read())
image_temp.flush()
my_temp.image.save(image_name, File(image_temp), save=True)
我没有覆盖 Mymodel 的保存方法并且 image_name 的值是 image-name.jpg
>> print image_name
u'image-name.jpg'
编辑:包括 Mymodel 代码
def _image_container(instance, filename):
return os.path.join(settings.IMAGE_FILES_ROOT, instance.slug + '.' + filename.split('.')[-1].lower())
class Mymodel(models.Model):
...
slug = AutoSlugField(_('Slug'), unique=True, populate_from='title', editable=True)
image = thumbnail.ImageField(_('Image'), upload_to=_image_container)
我想保留_image_container 功能,因为它在手动上传时效果很好
【问题讨论】:
-
它以您给它的名称 -'image-name.jpg' 保存。你期待什么?
-
@Rohan 不,它是用名称保存的 ` .jpg ` 而不是 ' image-name.jpg ` 这就是问题所在。没有保存名称,只是图像扩展名。
-
向我们展示
Mymodel()和upload_to属性的值。
标签: python django python-2.7 django-models django-views