[英]Django 'File' object has no attribute 'content_type'
我正在定義一個函數,用於為模型中上傳的每個圖像創建縮略圖。 下面是我的代碼:
def create_thumbnail(self):
if not self.coverphoto:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.coverphoto.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
elif DJANGO_TYPE == 'image/gif':
PIL_TYPE = 'gif'
FILE_EXTENSION = 'gif'
# Open original photo which we want to thumbnail using PIL's Image
image = Image.open(StringIO(self.coverphoto.read()))
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
# Save image to a SimpleUploadedFile which can be saved into
# ImageField
suf = SimpleUploadedFile(os.path.split(self.coverphoto.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
# Save SimpleUploadedFile into image field
self.coverphoto_thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf,save=False)
當我運行單元測試時,它顯示錯誤:
'File' object has no attribute 'content_type'
並且指示的錯誤行是:
DJANGO_TYPE = self.coverphoto.file.content_type
因為我從舊的django代碼段中獲得了這段代碼。 我認為這可能是由不同的Django版本引起的。
我可以知道如何在Django 1.6中檢查content_type嗎?
有解決這個問題的好方法嗎?
謝謝。
from mimetypes import MimeTypes
import urllib
mime = MimeTypes()
url = urllib.pathname2url(file_name)
mime_type = mime.guess_type(url)
我通過以下方式解決了它:
...
#DJANGO_TYPE = self.image.file.content_type
if self.image.name.endswith(".jpg"):
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
DJANGO_TYPE = 'image/jpeg'
elif self.image.name.endswith(".png"):
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
DJANGO_TYPE = 'image/png'
...
為我工作。 無需查找conten_type,而只需查看文件結尾。 如果需要.gif或其他,則需要查找正確的內容類型並添加其他self.image.name.endswith(".gif")
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.