【问题标题】:django: Save image from url inside another modeldjango:从另一个模型中的 url 保存图像
【发布时间】:2012-04-24 10:53:13
【问题描述】:
class Item(models.Model):
    name = models.CharField(max_length = 200)
    image = models.ImageField(upload_to = 'read', blank=True)
    creative_url = models.CharField(max_length = 200)
    description = RichTextField()

    def save(self, *args, **kwargs):
        content = urllib2.urlopen(self.creative_url).read()
        self.image.save("test.jpg", File(content))
        super(Item, self).save(*args, **kwargs)

给出例外: “str”对象没有属性“name”

我试图遵循这个答案(http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url)但这并没有帮助摆脱例外。


AttributeError at /admin/collection/item/1/ 'str' object has no attribute 'name' Request Method:    POST Request
URL:    http://127.0.0.1:8000/admin/collection/item/1/ Django
Version:    1.2.5 Exception Type:   AttributeError Exception Value:  'str'
object has no attribute 'name' Exception
Location:   D:\FF\django\core\files\base.py in _get_size, line 39 Python
Executable: C:\Python27\python.exe Python Version:  2.7.2 Python
Path:   ['D:\\FF',
'C:\\Python27\\lib\\site-packages\\django_social_auth-0.6.7-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\python_openid-2.2.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\oauth2-1.5.211-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\httplib2-0.7.4-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\selenium-2.20.0-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\ipython-0.12-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_localeurl-1.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pil-1.1.7-py2.7-win32.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs',
'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk', 'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'c:\\python27\\lib\\site-packages'] Server time:    Tue, 24 Apr 2012
14:19:00 +0300

【问题讨论】:

  • 请显示真正的异常和回溯。
  • 你发布了你的整个模型吗?听起来这与图像保存没有直接关系。您的模型上有 unicode 方法吗?

标签: python django


【解决方案1】:

你需要使用django.core.files.base.ContentFile而不是File

self.image.save("test.jpg", ContentFile(content), save=False)

File 接受具有size 属性的文件对象或StringIO 对象,或者您需要手动设置FileImageFilesize 属性以使其与StringIO 一起工作:

s = StringIO()
s.write(urllib2.urlopen(self.creative_url).read())
s.size = s.tell()
self.image.save('test.jpg', File(s), save=False)

另外,请注意self.image.save 中的save=False:默认情况下,save=True,这将导致包含图像字段的实例被保存。因此,您代码中的save 逻辑可能会遇到无限循环并达到最大递归深度。

【讨论】:

  • 喜欢你的回答,因为我在那个 inf 循环中:)
  • 很好的答案!虽然我不得不删除save=False,因为它导致图像无法保存到模型字段中,但是没有它它可以正常工作(可能是因为我使用了模型方法并且没有在.save()中覆盖?)
  • @Hybrid 是的,很有可能。
【解决方案2】:

尝试类似:

(假设在:Programmatically saving image to Django ImageField

from django.db import models
from django.core.files.base import ContentFile
import urllib2
from PIL import Image
from StringIO import StringIO

class Item(models.Model):
    name = models.CharField(max_length=200)
    image = models.ImageField(upload_to='read', blank=True)
    creative_url = models.URLField(max_length=200)

    class Meta:
        verbose_name = "Item"
        verbose_name_plural = "Items"

    def download_image(self, url):
        input_file = StringIO(urllib2.urlopen(url).read())
        output_file = StringIO()
        img = Image.open(input_file)
        if img.mode != "RGB":
            img = img.convert("RGB")
        img.save(output_file, "JPEG")
        self.image.save(self.name+".jpg", ContentFile(output_file.getvalue()), save=False)

    def save(self, *args, **kwargs):
        self.download_image(self.creative_url)
        super(Item, self).save(*args, **kwargs)

【讨论】:

    【解决方案3】:

    使用请求的解决方案

    from django.core.files.base import ContentFile
    from requests import request, HTTPError
    
    def save(self, *args, **kwargs):
        try:
            data = request('GET', self.creative_url,)
            data.raise_for_status()
            self.image.save('fname.jpg', ContentFile(data.content),save=False)
        except HTTPError:
            pass
        super(Item, self).save(*args, **kwargs)
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2010-11-05
      • 2015-01-25
      • 2018-11-01
      • 2015-02-27
      • 1970-01-01
      • 2021-03-26
      • 2015-01-31
      • 2022-10-14
      相关资源
      最近更新 更多