我是 Django 的初学者,这正是它的作用。我按照文档中的说明进行操作,但无论如何,也许出了什么问题?
从管理页面我添加\设置产品并选择“图像”,然后当我保存它时创建缩略图并尝试保存在“/media/uploads/”中,但它创建另一个“媒体”文件夹当站点路径为“/media/uploads/img.png”时,图像存储在“/media/media/uploads/img.png”中。这是代码:
/shop/settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # or even 'media/'
/shop/urls.py:
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
添加后,然后在我的产品模型中我这样做:
/apps/store/models.py:
class Product(models.Model):
...
image = models.ImageField(upload_to='media/uploads/', blank=True, null=True)
thumbnail = models.ImageField(upload_to='media/uploads/', blank=True, null=True)
...
def save(self, *args, **kwargs):
self.thumbnail = self.make_thumbnail(self.image)
super().save(*args, **kwargs)
@staticmethod
def make_thumbnail(image, size=(512, 512)):
if not image:
return
img = Image.open(image)
if img.mode in ('RGBA',): # converting image to RGB if it's RGBA
img.load()
rgb_convert = Image.new('RGB', img.size, 0)
rgb_convert.paste(img, mask=img.split()[3])
img = rgb_convert
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'PNG', quality=80)
thumb = File(thumb_io, name=image.name)
return thumb
我尝试将“upload_to”更改为“uploads/”,然后它以正确的方向存储文件,但现场路径也更改为“/uploads/img.png”,而它必须是“/media/uploads/img” .png'
有什么问题吗?谢谢!
牛魔王的故事
繁星淼淼
相关分类