If you set the debug mode to False on a server such as Heroku or GAE (Google App Engine), the static files provided by Django for development will not be provided and CSS, JS, img, etc. may not be displayed. There is.
So, I can solve this problem by uploading a static file to Google Cloud Storage, and I would like to explain how to do it.
Django Strage (Google Cloud Storage) Official Documentation https://django-storages.readthedocs.io/en/latest/backends/gcloud.html
Install Django Strage (Google Cloud Storage)
, a Django library for working with Google Cloud Strage on Django, with pip.
bash
$ pip install django-storages[google]
From Google Cloud Platform, register your Cloud Strage credentials and get a JSON file containing your credentials.
You can get it from the Google Start Guide (https://cloud.google.com/docs/authentication/getting-started).
step 1 From the link in the Google Start Guide (https://cloud.google.com/docs/authentication/getting-started), select "Go to the Create Service Account Key page"
Step 2 Enter the service account name in Create new service account. Then select "Storage"-> "Storage Administrator" from the role. Make sure that the key type is JSON, and click the "Create" button. This will download the JSON file.
** Place the downloaded JSON file in the root directory of your Django project. ** **
The unit of Cloud Strage is called a bucket (meaning like a bucket to put data in). Create this to store your data.
Google Cloud Console (Cloud Strage) https://console.cloud.google.com/storage/browser
If you access from the above URL, you will see the following creation screen, so create a new bucket.
When completed, the screen below will be displayed.
This completes the settings on the Google Cloud Platform console.
Set the default storage and bucket name in the settings.py file.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = '[YOUR_BUCKET_NAME_GOES_HERE]'
from google.oauth2 import service_account
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
os.path.join(BASE_DIR, '[YOUR_AUTHENTICATON_KEY_FILE_NAME].json'),
)
This completes the settings.
After that, let's execute the following command.
bash
$ python manage.py collectstatic
Then deploy the configuration changes to the server and it should work.
Thank you for your hard work.
Recommended Posts