django提交的图片来自url文件名存储错误

时间:2013-11-18 10:56:34

标签: python django python-2.7 django-models django-views

我正在尝试根据this question的答案提交来自网址的图片,但结果我成功存储了图片文件,但文件名为.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功能,因为它在手动上传时效果很好

1 个答案:

答案 0 :(得分:0)

你的upload_to _image_container函数会根据Mymodel实例的slug重命名图像,但是用于保存图像的模型实例没有slug,所以显然你确实拥有了你所要求的...长话短说,你必须明确地将临时Mymodel实例的slug属性设置为你想要的图像名称。

import os
extract_url = 'http://example.com/image-name.jpg'
image_name = extract_url.split('/')[-1]
slug = os.path.splitext(image_name)[0]
my_temp = Mymodel(slug=slug)

# etc