Django : 이미지 URL에서 ImageField에 이미지 추가
내 추악한 영어 실례합니다 ;-)
이 매우 간단한 모델을 상상해보십시오.
class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
이미지 URL에서 사진을 만들고 싶습니다 (즉, django 관리 사이트에서 손으로하지 않음).
다음과 같이해야한다고 생각합니다.
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)
말하지 않더라도 문제를 잘 설명했으면합니다.
감사합니다 :)
편집하다 :
이것은 작동 할 수 있지만 content
django 파일 로 변환하는 방법을 모르겠습니다 .
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/ 을 만들었습니다 . 코드는 urllib.urlretrieve가 기본적으로 오류 처리를 수행하지 않기 때문에 urllib2.urlopen을 사용한다는 점을 제외하면 위의 pithyless의 답변과 유사하므로 필요한 대신 404/500 페이지의 내용을 쉽게 얻을 수 있습니다. 콜백 함수 및 사용자 지정 URLOpener 하위 클래스를 만들 수 있지만 다음과 같이 내 임시 파일을 만드는 것이 더 쉽다는 것을 알았습니다.
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))
from myapp.models import Photo
import urllib
from urlparse import urlparse
from django.core.files import File
img_url = 'http://www.site.com/image.jpg'
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
# See also: http://docs.djangoproject.com/en/dev/ref/files/file/
photo.image.save(name, File(open(content[0])), save=True)
Chris Adams와 Stan이 말한 것을 결합하고 Python 3에서 작동하도록 업데이트하면 Requests 를 설치 하면 다음과 같이 할 수 있습니다.
from urllib.parse import urlparse
import requests
from django.core.files.base import ContentFile
from myapp.models import Photo
img_url = 'http://www.example.com/image.jpg'
name = urlparse(img_url).path.split('/')[-1]
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
response = requests.get(img_url)
if response.status_code == 200:
photo.image.save(name, ContentFile(response.content), save=True)
Django의 ContentFile 문서 및 Requests의 파일 다운로드 예제 에서 더 관련있는 문서 .
ImageField
is just a string, a path relative to your MEDIA_ROOT
setting. Just save the file (you might want to use PIL to check it is an image) and populate the field with its filename.
So it differs from your code in that you need to save the output of your urllib.urlopen
to file (inside your media location), work out the path, save that to your model.
I do it this way on Python 3, which should work with simple adaptations on Python 2. This is based on my knowledge that the files I’m retrieving are small. If yours aren’t, I’d probably recommend writing the response out to a file instead of buffering in memory.
BytesIO is needed because Django calls seek() on the file object, and urlopen responses don’t support seeking. You could pass the bytes object returned by read() to Django's ContentFile instead.
from io import BytesIO
from urllib.request import urlopen
from django.core.files import File
# url, filename, model_instance assumed to be provided
response = urlopen(url)
io = BytesIO(response.read())
model_instance.image_field.save(filename, File(io))
this is the right and working way
class Product(models.Model):
upload_path = 'media/product'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.image_url:
import urllib, os
from urlparse import urlparse
filename = urlparse(self.image_url).path.split('/')[-1]
urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
self.image = os.path.join(upload_path, filename)
self.image_url = ''
super(Product, self).save()
참고URL : https://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url
'program tip' 카테고리의 다른 글
양식없이 파일 업로드 (0) | 2020.09.25 |
---|---|
OrderedDict를 python3에서 일반 dict로 변환하는 방법 (0) | 2020.09.25 |
Gitolite로 만든 Git 저장소의 이름을 어떻게 바꾸나요? (0) | 2020.09.25 |
catch 블록에서 대기 (0) | 2020.09.25 |
C에서 문자열을 대체하는 기능은 무엇입니까? (0) | 2020.09.25 |