Django配置S3存储登录时报不支持绝对路径错误如何解决
报错解决方法
错误原因
你当前项目配置了S3兼容的对象存储(DigitalOcean Spaces)作为默认文件存储后端,这类远程存储服务不支持本地文件系统的绝对路径调用,你在Profile模型的save方法中使用self.image.path获取文件本地路径的操作直接触发了该报错。
修复步骤
1. 修正Profile模型的save方法
不再调用path属性,直接使用文件流处理图片缩略图,修改后的models.py代码如下:
from django.db import models from django.contrib.auth.models import User from PIL import Image from io import BytesIO from django.core.files.base import ContentFile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') role = models.CharField(default='user', max_length=20) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): # 首次保存获取文件对象 super().save(*args, **kwargs) # 直接读取远程存储返回的文件流,不调用path属性 img = Image.open(self.image.file) if img.width > 280 or img.height > 280: output_size = (280, 280) img.thumbnail(output_size) # 将处理后的图片写入内存 img_buffer = BytesIO() save_format = img.format if img.format else 'PNG' img.save(img_buffer, format=save_format) img_buffer.seek(0) # 覆盖保存原图片到远程存储,不重复触发save避免循环 self.image.save(self.image.name, ContentFile(img_buffer.read()), save=False) # 二次保存更新图片信息 super().save(*args, **kwargs)
2. 修正配置文件错误
你的cdn/conf.py中AWS_LOCATION配置未正确拼接变量,需要添加f前缀启用字符串格式化:
AWS_LOCATION = f"https://{AWS_STORAGE_BUCKET_NAME}.fra1.digitaloceanspaces.com"
额外注意事项
- 原代码中
__str__和save方法没有缩进进Profile类内部,会导致方法无法关联到模型,上述修改已经修正了缩进问题。 - 本地开发环境如果没有配置S3相关环境变量,可以单独设置开发环境使用本地文件存储,避免调试时需要依赖远程存储。
内容的提问来源于stack exchange,提问作者Michael Sylvester
相关产品推荐
相关产品推荐

