【问题标题】:django submit image fom url file name stored wrongdjango 从 url 文件名提交图像存储错误
【发布时间】: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


【解决方案1】:

您的 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

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2015-08-31
    • 2018-11-17
    • 2022-12-12
    相关资源
    最近更新 更多