问题描述
我目前在我的应用程序中使用django-storages来托管静态和媒体文件。我还在图像上传中使用imagekit来创建整个应用程序所需的图像的多个版本。
尝试序列化图像URL时出现问题。 DRF返回一个URL,例如http://127.0.0.1:8000/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg,当打开它时,它返回一个完全空白的页面。我真正需要的是返回“真实”存储网址,例如https://domain.s3.amazonaws.com/static/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg。
S3设置:
# aws settings
AWS_ACCESS_KEY_ID = 'secret'
AWS_SECRET_ACCESS_KEY = 'secret'
AWS_STORAGE_BUCKET_NAME = 'domain'
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
AWS_LOCATION = 'static'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),# os.path.join(BASE_DIR,'frontend/dist'),]
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN,AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MEDIA_ROOT = 'static/media'
MEDIA_URL = '/media/'
models.py
class Category(models.Model):
def upload_content_file_name(instance,filename):
"""
Return the location of which to upload the file
"""
return os.path.join('categories/%s/' % instance.name.lower(),filename)
name = models.CharField(
_('category name'),max_length=255,unique=False
)
...
image = models.ImageField(
_('image'),upload_to=upload_content_file_name,help_text=_(
'Category image,should only be used on top level parents!'
),blank=True,null=True,)
image_default = ImageSpecField(source='image',processors=[ResizeToFill(375,375)],format='JPEG',options={'quality': 90})
image_sm = ImageSpecField(source='image',processors=[ResizeToFill(640,300)],options={'quality': 90})
image_md = ImageSpecField(source='image',processors=[ResizeToFill(768,366)],options={'quality': 90})
image_lg = ImageSpecField(source='image',processors=[ResizeToFill(1024,480)],options={'quality': 90})
image_xl = ImageSpecField(source='image',processors=[ResizeToFill(1280,600)],options={'quality': 90})
...
serializers.py
class CategorySerializer(serializers.ModelSerializer):
image_default = serializers.ImageField(read_only=True)
image_sm = serializers.ImageField(read_only=True)
image_md = serializers.ImageField(read_only=True)
image_lg = serializers.ImageField(read_only=True)
image_xl = serializers.ImageField(read_only=True)
class Meta:
model = Category
fields = (
...
'image','image_default','image_sm','image_md','image_lg','image_xl',)
解决方法
上传的文件不是静态文件,而是媒体文件, 请注意,您对媒体文件的设置已关闭
A B C
1 2 Na
Na 8 Na
Na 0 Na
Na 0 Na
Na 0 8
Na 4 9
当您将它们与静态对象进行比较
MEDIA_ROOT = 'static/media'
MEDIA_URL = '/media/'