尝试从本地路径将文件上载到FileField
时遇到问题
我已在S3
bucket中正确配置了CDN后端,并将其用作我的一个模型字段的PrivateMediaStorage
:
class MyModel(models.Model):
some_file = models.FileField(storage=PrivateMediaStorage())
...
使用这个非常简单的配置,每当我通过django-admin
创建/更新模型时,它都会被保存,并且作为some_file
附加的文件会正确地上传到S3
bucket
然而,如果我尝试以编程方式创建/更新模型实例,比如说通过自定义manage.py
命令,则会创建模型实例本身,但不会将附件上载到CDN。下面是我用来上传文件的代码的简化版本:
class Command(BaseCommand):
help = 'Creates dummy instance for quicker configuration'
def handle(self, *args, **options):
some_file = os.path.join(os.path.dirname(__file__), '../../../temporary/some_image.png')
if not os.path.exists(some_file):
raise CommandError(f'File {some_file} does not exist')
else:
instance, created = MyModel.objects.get_or_create(defaults={'some_file': some_file}, ...)
我的实现中缺少了什么,需要调整什么以允许从本地存储上载文件
您正在向} 对象
some_file
字段传递一个字符串(os.path.join()
的结果),但需要向其传递一个实际的^{直接在模型上保存文件的最简单方法是使用^{}'s ^{} 方法
作为上述案例的工作解决方案,创建记录的有效方法是:
或者更好地使用
pathlib
动态获取名称:请注意,基于文件获取行不太可能起作用,因为每次打开文件时,使用
File
实例作为参数执行get_or_create()
可能每次都会创建一个新行。最好将文件字段放入defaults
:您也可以这样做。
相关问题 更多 >
编程相关推荐