问题描述
请原谅我丑陋的英语;-)
please excuse me for my ugly english ;-)
想象一下这个非常简单的模型:
Imagine this very simple model :
class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
我想从图像 URL 创建一张照片(即,不是在 django 管理站点中手动创建).
I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).
我认为我需要做这样的事情:
I think that I need to do something like this :
from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
我希望我已经很好地解释了这个问题,如果没有告诉我.
I hope that I've well explained the problem, if not tell me.
谢谢:)
这可能有效,但我不知道如何将 content
转换为 django 文件:
This may work but I don't know how to convert content
to a django File :
from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
推荐答案
我刚刚创建了 http://www.djangosnippets.org/snippets/1890/ 对于同样的问题.该代码类似于上面的 pithyless' 答案,除了它使用 urllib2.urlopen 因为 urllib.urlretrieve 默认不执行任何错误处理,因此很容易获取 404/500 页面的内容而不是您需要的内容.您可以创建回调函数 &自定义 URLOpener 子类,但我发现像这样创建自己的临时文件更容易:
I just created http://www.djangosnippets.org/snippets/1890/ for this same problem. The code is similar to pithyless' answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn't perform any error handling by default so it's easy to get the contents of a 404/500 page instead of what you needed. You can create callback function & custom URLOpener subclass but I found it easier just to create my own temp file like this:
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
im.file.save(img_filename, File(img_temp))
这篇关于Django:从图像 url 在 ImageField 中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!