我在django-storages中遇到问题。我的图片网址正由字段返回,但是转到网址时,我得到了NoSuchKey。奇怪的是,当为静态文件配置此文件(请参见最后一个代码块)并执行collectstatic
时,一切都可以正常上传。 django-storages / boto不返回任何错误。
这是我的settings.py
:
AWS_ACCESS_KEY_ID = ""
AWS_SECRET_ACCESS_KEY = ""
AWS_STORAGE_BUCKET_NAME = ""
AWS_BUCKET_ACL = "public-read"
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_QUERYSTRING_AUTH = False
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
AWS_LOCATION = 'media'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
AWS_DEFAULT_ACL = "public-read"
视图:
@login_required
def addface(request, personid):
person = models.Person.objects.get(pk=personid)
form = FaceForm(request.POST, request.FILES)
if request.method == "POST":
if form.is_valid():
try:
# this prints the url that returns the error
print(form.instance.image.url)
# some processing, ignore this
faces = Person(person.name, person.personid, "1").detect(
form.instance.image.url)
# Should only be one face per image
if len(faces) != 1:
messages.add_message(request, messages.ERROR, "More than one face detected!")
# Break out of loop, go straight to render
raise SystemExit
faces[0].add()
form.save(commit=False)
form.instance.person = person
form.instance.faceid = faces[0].faceid
form.save()
except Exception as e:
if e is not SystemExit:
messages.add_message(request, messages.ERROR,
ERR)
raise e
else:
form = FaceForm()
return render(request, "findapp/addface.html",
{"form": form, "faces": models.Face.objects.filter(person=person), "errors": form.errors,
"name": person.name})
表格:
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<input type="file"
multiple
name="image">
<button type="submit" class="px-4 py-4 rounded bg-gray-300 text-gray-600 hover:shadow">Add
files
</button>
</form>
和模型:
class Face(models.Model):
person = models.ForeignKey('Person', on_delete=models.CASCADE)
image = models.ImageField()
faceid = models.TextField()
AWS权限(我也未选中阻止所有公共访问的框):
{
"Version": "2008-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::name/*",
"arn:aws:s3:::name"
]
}
]
}
还有我以前的静态文件settings.py(我只对存储媒体感兴趣):
AWS_ACCESS_KEY_ID = ""
AWS_SECRET_ACCESS_KEY = ""
AWS_STORAGE_BUCKET_NAME = ""
AWS_BUCKET_ACL = "public-read"
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_QUERYSTRING_AUTH = False
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
AWS_LOCATION = 'media'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
AWS_DEFAULT_ACL = "public-read"