简体   繁体   English

使用django-storages boto3将文件动态上传到不同的s3存储桶中

[英]Upload files dynamically into different s3 buckets with django-storages boto3

I'm using django-storages to upload into an s3 bucket. 我正在使用django-storages上传到s3存储桶。 But I want to be able to upload into a different s3 bucket than what I have set in my default in settings.py My app has a different web page for each bucket and can access the contents. 但是我希望能够上传到与我在settings.py中的默认设置中设置不同的s3存储桶中。我的应用程序对每个存储桶都有不同的网页,并且可以访问其中的内容。 Ideally I would want to pull the bucket name from the url and dynamically set the bucket name to where the file is being uploaded in my code. 理想情况下,我想从网址中提取存储桶名称,并将其动态设置为代码中要上传文件的位置。

    def post(self, request, *args, **kwargs):
    if request.method == "POST":
        bucket = kwargs.get('bucket_name')
        form_model = Document()
        form_model.upload.storage = S3Boto3Storage(bucket=bucket)
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    return HttpResponseRedirect("/bucket/"+bucket)

This only saves to the defaul location 这只会保存到默认位置

    def post(self, request, *args, **kwargs):
    if request.method == "POST":
        bucket = kwargs.get('bucket_name')
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.upload.storage = S3Boto3Storage(bucket=bucket)
            form.save()
    return HttpResponseRedirect("/bucket/"+bucket)

Found my own answer 找到了我自己的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM