Images are not displayed properly even when using ImageField on servers such as Heroku and GAE (Google App Engine).
This is because SQL doesn't support uploading images, and you'll have to upload images to cloud storage such as Google Cloud Strage or Amazon S3 to resolve this.
This time, I will show you how to upload images to Google Cloud Storage.
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'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
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