在Django中使用Amazon S3上传带ImageField的图片

6 投票
1 回答
10683 浏览
提问于 2025-04-18 10:11

我用pip安装了django-storages(命令是pip install django-storages)

然后我设置了AWS的相关配置:

DEFAULT_FILE_STORAGE = 'storages.backends.s3.S3Storage'
AWS_STORAGE_BUCKET_NAME = 'bar.media'
AWS_ACCESS_KEY_ID = 'MyAwesomeKeyId'
AWS_SECRET_ACCESS_KEY = 'BlahBlahBlah'

我的模型是这样的:

def Bar(Model):
   image = models.ImageField(upload_to='bar')

在forms.py文件里:

 class BarForm(forms.Form):
     image = forms.FileField(label='Logo',required=False)
     def __init__(self, *args, **kwargs):
            super(BarForm, self).__init__(*args,**kwargs)
            self.fields['image'].label='My Awesome Photo'

在views.py文件里:

     @csrf_exempt
     def bar_web(request):
         context = {}
         if request.method == 'POST':
            form = BarForm(request.POST, request.FILES)
            context['form'] = form
            if form.is_valid():
                    try:
                            logoFile = request.FILES['image']
                            print 'PIC: '+str(logoFile)
                    except:
                            logoFile = False 
                    if logoFile:
                          bar = Bar(image=logoFile)
                          bar.save()
                          bar.reload()

在模板里:

         <p>Image Name: {{bar.image.name}}</p>
         <p>Image Url: {{bar.image.url}}</p>
         <p>Image : {{bar.image.content_type}}</p>
         <p>Image Path: {{bar.image.path}}</p>

但是没有任何输出。

我现在能看到文件名被打印出来了,但在s3上没有任何文件被上传。

我没看到的错误是什么呢?

1 个回答

6

我的问题是IAM配置错了;这些视频可能对其他用户有帮助...

https://www.youtube.com/watch?v=JuffWMBeJkw

撰写回答