1
votes

I am running a File manager app on Local machine using Google Cloud Sql Proxy and storing the files in a Google Cloud Storage bucket. The file is being saved in the bucket, but the FileField is set to "null". I want it to show the url by which I can access the file.

I am following this answer Configure Django and Google Cloud Storage?

I have set the Google Cloud Storage bucket to public.

Django Model:

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

Setting.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)

Expected Result:

{
    "id": 13,
    "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf",
}

Actual Result:

{
    "id": 13,
    "docfile": null,
}

If I change my Settings.py to (uncomment line 1,2. Comment line 4), the file is saved on my local machine media/ folder, and "docfile" is set to the 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)

I get the output:

{
    "id": 13,
    "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf",
}
1

1 Answers

1
votes

It seems that you're not configuring the settings.py file correctly. Check this documentation to use Google Cloud Storage Bucket for Djanjo project.

As you can see in the documentation, settings.py should be like this:

settings.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,
)
......

Let me know if it works for you.