更新时Django文件字段未将文件保存到S3存储键文件夹

发布于 2025-02-07 22:13:57 字数 509 浏览 2 评论 0原文

我将文件上传到以下路径中的S3存储桶:

bucket/folder/{custom_id}/file

I具有以下方法,我在模型中调用。在DRF Post方法中,该文件已正确保存到S3,我可以检索GET的路径。但是,当我尝试将新文件上传到put方法中时,文件名被保存在DB中,但是该文件并未保存在S3存储桶中。

自定义上传路径

    def upload_path_handler(instance, filename):
        return f'{FILES_FOLDER}/{id}/{filename}'

In Models.py

cc_file = models.FileField(
    db_column='CCFilename', blank=True, null=True, upload_to=upload_path_handler

此方法在DRF的post API呼叫中起作用。如果在字段的更新上更改了文件,则如何将新文件保存到S3。

I am uploading file to s3 bucket in the below path:

bucket/folder/{custom_id}/file

I have the below method which I am calling in Model. In DRF Post method, the file is getting saved correctly to s3 and I am able to retrieve the path in GET. But when I try to upload new files in PUT method, the filename is getting saved in db, but the file is not saving in s3 bucket.

custom upload path

    def upload_path_handler(instance, filename):
        return f'{FILES_FOLDER}/{id}/{filename}'

In Models.py

cc_file = models.FileField(
    db_column='CCFilename', blank=True, null=True, upload_to=upload_path_handler

)

This method is working in POST API call of DRF. How do I save new file to s3 if the file is getting changed on update of the field.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国粹 2025-02-14 22:13:58

您可以尝试什么..

1。确保您拥有正确的S3权限和政策。通过AWS S3控制台中的“策略”访问您的特定桶中的“策略”。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<your_bucket_name>/*"
        },
        {
            "Sid": "Statement2",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::<your_bucket_name>/images/"
        }
    ]
}

2。安装Whitenoisemiddleware&amp; django-storage in您的项目环境中。

pip install whitenoise
pip install django-storages

3。将以下内容添加到Middleware =中的settings.py

'whitenoise.middleware.WhiteNoiseMiddleware',

4。在settings.py中添加以下添加才能正确处理S3的URL。处理由Django中间件&amp;完成。 Django-storage自动

STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % os.environ['BUCKET_NAME']
AWS_ACCESS_KEY_ID = os.environ['AWS_KEY']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_ACC_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['BUCKET_NAME']
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

MEDIA_ROOT = os.path.join (BASE_DIR, 'static/images/')
STATIC_ROOT = os.path.join (BASE_DIR, 'static')

STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)

5。将上传到精确的S3存储夹文件夹中。 (附加)

在设置中。PySet Media root:

MEDIA_ROOT = os.path.join (BASE_DIR, 'static/images/')

in Models.py使用Imagefiled并添加upload_to =将文件夹名称添加并创建它是第一个上传!:

image_variable = models.ImageField(null=True, default="{default_filename)", upload_to='uploads/') 

参考: django-storages , s3访问故障排除

What you can try..

1. Make sure you have the right S3 Permissions and Policy in place. Access 'Policy' via permissions tab in AWS S3 console for your specific bucket.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<your_bucket_name>/*"
        },
        {
            "Sid": "Statement2",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::<your_bucket_name>/images/"
        }
    ]
}

2. Install WhiteNoiseMiddleware & django-storages in your project environment.

pip install whitenoise
pip install django-storages

3. Add the following to MIDDLEWARE= in settings.py

'whitenoise.middleware.WhiteNoiseMiddleware',

4. Following additions in settings.py are required to handle URLs from S3 correctly. The handling is done by django middleware & django-storages automatically

STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % os.environ['BUCKET_NAME']
AWS_ACCESS_KEY_ID = os.environ['AWS_KEY']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_ACC_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['BUCKET_NAME']
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

MEDIA_ROOT = os.path.join (BASE_DIR, 'static/images/')
STATIC_ROOT = os.path.join (BASE_DIR, 'static')

STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)

5. For aiming uploads into a precise S3 Bucket folder. (Additional)

In setting.py set media root:

MEDIA_ROOT = os.path.join (BASE_DIR, 'static/images/')

In models.py use ImageFiled and add upload_to= takes in a folder name and creates it with the first upload!:

image_variable = models.ImageField(null=True, default="{default_filename)", upload_to='uploads/') 

Reference: django-storages , whiteNoiseMiddelware, S3 Access Troubleshooting

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文