PostgreSQL and My Django app on heroku is not synching - django

I have a django made app on heroku and I want change the database there from sqlite to postgreSQL.
I have changed the code in setting.py as follows however the data in my local sqlite is still uploaded to heroku.
from socket import gethostname
hostname = gethostname()
if "MY-COMPUTER-NAME" in hostname: #my computer name
# debug
# DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
else:
# online
# DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES = {
'default': dj_database_url.config()
}
ALLOWED_HOSTS = ['*']
My commands to deploy
git add -A
git commit -m "Change"
git push heroku master
heroku ps:scale web=1
heroku run python manage.py migrate
heroku open
this is a full code of srtting.py
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/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 = ['*']
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"blog",
]
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 = "personal_portfolio.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["personal_portfolio/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 = "personal_portfolio.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
from socket import gethostname
hostname = gethostname()
if "MY-COMPUTER-NAME" in hostname: #my computer name
# debug
# DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
else:
# online
# DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES = {
'default': dj_database_url.config()
}
ALLOWED_HOSTS = ['*']
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/' # css
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
django_heroku.settings(locals())
try:
from .local_settings import *
except ImportError:
pass
if not DEBUG:
SECRET_KEY = os.environ['SECRET_KEY'] #new
import django_heroku
django_heroku.settings(locals())

Related

django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured

django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alumni_portal.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
setting.py
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR2,'templates')
STATIC_DIR = os.path.join(BASE_DIR2, 'static')
# 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 = 'django-insecure-nj#^0^n%be!u=8!o5ui7efi*b7)iad2(jgw06^flv=z4i$z%7_'
# 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',
'portal',
'ckeditor',
'ckeditor_uploader',
'crispy_forms',
'django_social_share',
'import_export',
]
# CKEDITOR_UPLOADER_PATH = 'media/'
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 = 'alumni_portal.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 = 'alumni_portal.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbs',
'HOST': '127.0.0.2',
'PORT': '3300',
'USER': 'root',
'PASSWORD': 'Jamal#123',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'init_command': "set FOREIGN_KEY_CHECKS = 0;",
}
}
}
# 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_DIRS = [
STATIC_DIR
]
STATIC_ROOT = os.path.join(BASE_DIR, "/static")
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR2, 'uploads')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
AUTH_USER_MODEL = 'portal.User'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'dashboard'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
'default': {
'height': '100%',
'width': '100%',
},
}
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = '19ita57#karpagamtech.ac.in'
EMAIL_HOST_PASSWORD = 'Jamal#123'
Guys can help me to solve this error
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Css is not reflected when deploying django on heroku

I wrote the code in settings.py as below, but the css was not reflected. I also ran $ heroku run python manage.py collectstatic, but when I looked at heroku run bash, there were no static files. Please tell me how to deal with it.
settings.py
from pathlib import Path
import os
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
]
from socket import gethostname
hostname = gethostname()
if "User-MacBookAir.local" in hostname:
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ALLOWED_HOSTS = ['*']
else:
DEBUG = False
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES = {
'default': dj_database_url.config()
}
ALLOWED_HOSTS = ['.herokuapp.com']
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

Production not the same as local

When running locally my files are correct but on production it seems that none of the changes are through. I might be forgetting to do something to make the production files the same as local. Changed inbox.html to another file name.
TemplateDoesNotExist at /
inbox.html
Request Method: GET
Request URL: https://url.com/
Django Version: 3.2.9
Exception Type: TemplateDoesNotExist
Exception Value:
inbox.html
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py, line 84, in reraise
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.9.6
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python39.zip',
'/app/.heroku/python/lib/python3.9',
'/app/.heroku/python/lib/python3.9/lib-dynload',
'/app/.heroku/python/lib/python3.9/site-packages']
Server time: Tue, 01 Feb 2022 16:02:49 -0800
settings.py
"""
Django settings for portfolio project.
Generated by 'django-admin startproject' using Django 3.2.9.
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
# 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!
import os
#Gets rid of
from decouple import config
SECRET_KEY = config("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#DEBUG = config('DJANGO_DEBUG',default=True, cast=bool)
ALLOWED_HOSTS = ["url.com",'127.0.0.1','localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'social_django',
'formtools',
'phonenumber_field',
'pages.apps.PagesConfig',
'storages',
'django_cleanup.apps.CleanupConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', #new
]
ROOT_URLCONF = 'portfolio.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',
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect', # <--
],
},
},
]
WSGI_APPLICATION = 'portfolio.wsgi.application'
# 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/
# Swapped to Canada
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Canada/Pacific'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# All of this is in my console.aws.amazon to configure aws s3 static files
# If I am in prod DEBUG==false
# IAM Management Console
if DEBUG:
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
# Amazon S3 Buckets
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_DEFAULT_ACL = None
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_STATIC_LOCATION = 'static'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
STATICFILES_STORAGE = 'portfolio.storage_backends.StaticStorage'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION )
DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.MediaStorage'
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL= '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'pages/static'),
]
# Fixes Found another file with the destination path
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
#'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#Adding social logins
AUTHENTICATION_BACKENDS = ['social_core.backends.google.GoogleOAuth2','django.contrib.auth.backends.AllowAllUsersModelBackend',]
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# Extends default user with additional fields
AUTH_USER_MODEL = 'pages.Profile'
SOCIAL_AUTH_USER_MODEL = 'pages.Profile'
# social auth configs for google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_OAUTH2_KEY')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_OAUTH2_SECRET')
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/calendar']
SOCIAL_AUTH_JSONFIELD_ENABLED = True
SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline',}
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
# Todo:Add a postgresql for prod settings using Amazon RDS Management Console
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
SESSION_ENGINE = (
'django.contrib.sessions.backends.cache'
)
"""
SESSION_COOKIE_AGE = 60 # change expired session
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
"""
import django_heroku
django_heroku.settings(locals(), staticfiles=False)
I changed Inbox.html to another file name but running heroku bash seems like nothing changes.
Running bash on ⬢ arundeepchohan... up, run.9168 (Free)
~ $ ls
google-credentials.json manage.py pages portfolio Procfile Procfile.windows requirements.txt runtime.txt
~ $ cd pages
~/pages $ ls
admin.py calendar.py googleCalendarAPI.py migrations __pycache__ templates urls.py
apps.py forms.py __init__.py models.py static tests.py views.py
~/pages $ cd templates
~/pages/templates $ ls
adminControls.html dashboard.html editProfileModal.html Inbox.html sendMessageForm.html
base.html documents.html googleCalendar.html pickUserType.html sidebar.html
bookAppointment.html editProfileForm.html home.html registration
~/pages/templates $ exit
exit
So I added it to Github. Then I used the automatic deploy function from Heroku to connect it to that repository. Which did allow my heroku run bash to pick up the newly generated files. The only issues now are production database values are now not migrated properly.

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

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