我正在使用Google Cloud Sql Proxy在本地机器上运行文件管理器应用程序,并将文件存储在Google Cloud存储桶中。文件保存在bucket中,但FileField设置为"null"。我希望它显示我可以访问该文件的url。
我遵循这个答案配置Django和谷歌云存储?
我已经将谷歌云存储桶设置为公共存储桶。
Django模型:
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
设置.py:
#MEDIA_URL = "/media/"
#MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = 'printhub-files'
GS_PROJECT_ID = 'preasy-53c43'
GS_MEDIA_BUCKET_NAME = 'printhub-files'
# GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>'
# STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME)
MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME)
预期结果:
{
"id": 13,
"docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf",
}
实际结果:
{
"id": 13,
"docfile": null,
}
如果我将Settings.py更改为(取消注释第1,2行。注释行4(,文件保存在我的本地机器媒体/文件夹上,"docfile"设置为bucket url:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = 'printhub-files'
GS_PROJECT_ID = 'preasy-53c43'
GS_MEDIA_BUCKET_NAME = 'printhub-files'
# GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>'
# STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME)
MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME)
我得到输出:
{
"id": 13,
"docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf",
}
您似乎没有正确配置settings.py文件。查看此文档以使用Djanjo项目的谷歌云存储桶。
正如您在文档中看到的,settings.py应该是这样的:
设置.py
.....
GCS_ROOT = "https://storage.googleapis.com/{bucket_name}/".format(
bucket_name=os.environ.get("GCS_BUCKET")
)
MEDIA_PREFIX = "media"
MEDIA_URL = "{gcs_root}{prefix}/".format(
gcs_root=GCS_ROOT,
prefix=MEDIA_PREFIX,
)
......
让我知道它是否适合你。