django not switching to Postres when deploying to Heroku - django

I deployed my django app with Heroku and I am having troubles with connecting to Postgres.
If I run python manage.py createsuperuser after running heroku ps:exec --app produceit (so I am inside the Heroku instance's terminal), it says that I successfully created a superuser but nothing is written into Heroku Postgress DB...so I can't login into neither /admin nor my app.
I therefore run
heroku ps:exec --app produceit
python manage.py shell
from mywebsite.settings import DATABASES
and it seems like the settings.py has the variable DATABASE still connected to sqlite (see pic)
Funny enough, if I hardcode an admin into Heroku's Postgres DB, loging and then create an instance of one of my models from the app itself (like I create a blog's post)...it actually writes into Postgres and I see it on the Front End.
So basically it's like the app is working on Postgress BUT the terminal is running on SQLite.
What can I do? My settings are below
"""
Django settings for mywebsite project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'action.apps.ActionConfig',
'django_extensions',
'bootstrap_modal_forms',
'widget_tweaks',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#'whitenoise.middleware.WhiteNoiseMiddleware'
]
ROOT_URLCONF = 'mywebsite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mywebsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql',
# 'NAME': '',
# 'HOST': '',
# 'PORT': 5432,
# 'USER': '',
# 'PASSWORD': '',
# }
# }
# Parse database configuration from $DATABASE_URL
#import dj_database_url
#db_from_env = dj_database_url.config(conn_max_age=500)
#DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
#DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
import django_on_heroku
django_on_heroku.settings(locals())
#SECURE_SSL_REDIRECT=True
#SESSION_COOKIE_SECURE=True
#CSRF_COOKIE_SECURE=True
#SECURE_HSTS_SECONDS = 31536000
#SECURE_HSTS_INCLUDE_SUBDOMAINS=True
#SECURE_HSTS_PRELOAD=True
#import django_heroku
#django_heroku.settings(locals())

To get the correct environment variables etc., connect to the terminal via the Heroku dashboard and try it again. You can find it in "More" > "Run Console" > Type in "Bash" on your Heroku-app.

Related

deploying django to heroku :page not found error

I have been making a django app, and am now trying to deploy it to heroku. However when I go on it,says page not found
the resources not found on the server
and i am trying it on different app error remains same
Here is my settings.py (at learst the relevant parts, but please ask if you would like the rest):
"""
Django settings for django_deployment project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['django-deployment85.herokuapp.com','127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"whitenoise.middleware.WhiteNoiseMiddleware",
]
ROOT_URLCONF = 'django_deployment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_deployment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
#STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
django_heroku.settings(locals())
#and here is my requirement.txt
asgiref==3.4.1
backports.entry-points-selectable==1.1.1
certifi==2021.10.8
distlib==0.3.4
dj-database-url==0.5.0
Django==4.0
django-heroku==0.3.1
filelock==3.4.0
gunicorn==20.1.0
pipenv==2021.11.23
platformdirs==2.4.0
psycopg2==2.9.3
python-decouple==3.6
six==1.16.0
sqlparse==0.4.2
tzdata==2021.5
virtualenv==20.10.0
virtualenv-clone==0.5.7
virtualenvwrapper-win==1.2.6
waitress==2.0.0
whitenoise==6.0.0
Also, when I run the app locally with python manage.py runserver it works fine, it only doesn't work when I use heroku.
Please tell me if you need anymore information.
You may have postgres in Heroku, but your settings.py shows that you are still using SQLite. The DATABASES section should look like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database_name_goes_here',
'USER': 'username_goes_here',
'PASSWORD': 'password_goes_here',
'HOST': 'localhost',
'PORT': '',
}
}
The database name, user, and password you can get by going to your database, then click settings, then credentials.
There are several steps to deploying Django on Heroku. Configuring Postgres is just one. There's a nice tutorial at https://dev.to/giftedstan/heroku-how-to-deploy-a-django-app-with-postgres-in-5-minutes-5lk.

Internal Server Error (500) showing on sub-routes when running Django on server

I'm hosting my Django application on a VPS and I'm using Django Rest Framework and the Django Admin Site.
Everything seemed working running fine (check the below image),
but when I try to click on my API's I'm redirected to a Server Error (500) page.
One thing to notice is that when I'm running the app locally on my machine everything is working fine.
Below is my settings.py if it can help in anyway:
Django settings for thepatron project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import datetime
from dotenv import load_dotenv
# Initialize environment variables
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
try:
SECRET_KEY = str(os.getenv('SECRET_KEY'))
except KeyError as e:
raise RuntimeError("Could not find a SECRET_KEY in environment") from e
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
# VPS
'194.5.159.80',
# the-patron
'the-patron.com'
# Heroku
'https://the-patron-backend.herokuapp.com/',
# Hostinger IP Address
'141.136.43.2',
# Home IP Address
'127.0.0.1',
# Local Frontend Port
'localhost:4200',
]
AUTH_USER_MODEL = 'store.User'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
# CORS_ORIGIN_ALLOW_ALL = False
# CORS_ORIGIN_WHITELIST = (
# 'http//:localhost:8000',
# )
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'django_filters',
'store',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect
CORS_ALLOW_CREDENTIALS = True
ROOT_URLCONF = 'thepatron.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates/'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'thepatron.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
# Database settings to connect to hosted database
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': str(os.getenv('DATABASE_NAME')),
'USER': str(os.getenv('DATABASE_USER')),
'PASSWORD': str(os.getenv('DATABASE_PASS')),
'HOST': '141.136.43.2',
'PORT': '3306',
'OPTIONS': {
'sql_mode': 'traditional',
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
if DEBUG:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'store/static/store'),
os.path.join(BASE_DIR, 'staticfiles/restframework'),
]
else:
# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# URL to use when referring to static files located in STATIC_ROOT.
STATIC_URL = '/static/'
# MEDIA_ROOT is for server path to store files in the computer.
# This is where the backend loads media like images from
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/store/media')
# MEDIA_URL is the reference URL for browser to access the files over Http.
MEDIA_URL = '/media/'
STATICFILES_STORAGE = [
'django.contrib.staticfiles.storage.StaticFilesStorage',
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
],
'DEFAULT_AUTHENTICATION_CLASSES':
('rest_framework_simplejwt.authentication.JWTAuthentication', )
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600),
}
# Activate Django-Heroku.
django_heroku.settings(locals())
This works for me
In settings.py
DEBUG = True

I can't seem to find a way to write into heroku's postgres from my django app

I wrote an app with Django and it has been working fine when running locally. I know deployed it with Heroku and the app run as well.
However, I when I python manage.py createsuperuser it says that I successfully created the superuser but nothing is written into Heroku Postgress DB...so I can login into neither /admin nor my app.
I have been trying debugging like crazy but I can't find the issue. Especially because if I query the DB from django Shell I do see my account, but if I check the Postgress DB of Heroku I don't.
I also checked what DB my python shell is connected to and it seems that it's sqlite, not postgres.
How do I change it so that it connects to postgres?
Also, why is it connected to Sqlite on my shell but if I try to loging on adming it checks if my user extist on postgres?
This is my settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ...
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
#DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'action.apps.ActionConfig',
'django_extensions',
'bootstrap_modal_forms',
'widget_tweaks',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mywebsite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mywebsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Parse database configuration from $DATABASE_URL
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
#DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#import django_on_heroku
#django_on_heroku.settings(locals())
import django_heroku
django_heroku.settings(locals())
Okay, so I've had this very issue so many times when I was trying to upload my website to Heroku. It worked for me the last time when I did something like this:
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '...',
'HOST': '...',
'PORT': 5432,
'USER': '...',
'PASSWORD': '...',
The name, host, user and password can all be found when you create a postresql add on in Heroku itself. You will probably already have a postres add on as default. If not you can add it yourself. You may want to search for YouTube videos, as I found this all from there. I'm not able to remember which one, but if I do, I will link it here.
When you go to your app in Heroku, go to settings and click reveal config vars. Copy the link of the db and paste it somewhere so you can use it as reference. It will be something like this.
postgres://USER:PASSWORD#HOST:PORT/NAME
It sounds like you may be creating a superuser on your local instance rather than on the version on Heroku. Give this a try to create a Django superuser on your Heroku hosted site.
heroku run python manage.py createsuperuser

How to fix Nginx 502 Bad Gateway? -- Django Google App Deployment

Overview: After successfully completing this google app deployment documentation I run the last code within the documentation. -- $ gcloud app deploy -- After a few minutes waiting for the app to deploy I get this "502 badgateway nginx". Im currently on a MacBook Pro (Big Sur). Does anyone have a suggestion on how this problem may be resolved?
Here is my settings.py:
"""
Django settings for HealthHelper_site project.
Generated by 'django-admin startproject' using Django 3.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
#This is the original settings.py that was swapped with one to work and connect with
#Google's console... this is the orignal copy of the django settings.py file
from pathlib import Path
from decouple import config
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'main.apps.MainConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'HealthHelper_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'HealthHelper_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=
Here is my requirements.txt below:
Django==3.2.4
django-environ==0.4.5
psycopg2-binary==2.8.6
google-cloud-secret-manager==2.5.0
PyMySQL==1.0.2
mysqlclient==1.4.1
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=
If any other information needed please let me know!

django.db.utils.OperationalError: could not translate host name "postgis-container" to address

I am trying to build an image in django that will later be deployed on a digitalocean droplet with my own domain name. I am currently trying to get rid of an issue that I believe is affecting my progress in relation to my local postgis container. I have a container named: postgis-container in the network: awm. After I run:
python manage.py makemigrations
I get the error:
django.db.utils.OperationalError: could not translate host name "postgis-container" to address: Temporary failure in name resolution
I was told by my lecturer to use the network alias for the ALLOWED_HOSTS field in my settings.py but it didn't make any difference. I put a comment to the right hand side of the possible offending line.
settings.py
"""
Django settings for AdvancedWebMapping project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
import socket
from pathlib import Path
import docker_config
from whitenoise.storage import CompressedManifestStaticFilesStorage
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = docker_config.SECRET_KEY
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'world',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'AdvancedWebMapping.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'AdvancedWebMapping.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'HOST': 'localhost',
'USER': 'docker',
'PASSWORD': 'docker',
'PORT': '25432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
if socket.gethostname() =="matthew#acer":
DATABASES["default"]["HOST"] = "localhost"
DATABASES["default"]["PORT"] = 25432
else:
DATABASES["default"]["HOST"] = "postgis-container" # offending line?
DATABASES["default"]["PORT"] = 5432
# Set DEPLOY_SECURE to True only for LIVE deployment
if docker_config.DEPLOY_SECURE:
DEBUG = False
TEMPLATES[0]["OPTIONS"]["debug"] = False
ALLOWED_HOSTS = ['.matthewmawm.xyz', 'localhost', '209.97.133.19']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CORS_ORIGIN_ALLOW_ALL = True
else:
DEBUG = True
TEMPLATES[0]["OPTIONS"]["debug"] = True
ALLOWED_HOSTS = ['*', ]
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
how I created the postgis container (docker):
sudo docker create --name postgis-container --network awm --network-alias postgis-container -t -p 25432:5432 -v name_of_volume:/var/lib/postgresql kartoza/postgis
My own mistake. My hostname was incorrect at socket.gethostname().