Following the documentation and online tutorials on setting up my gunicorn.service results in ModuleNotFoundError: No module named 'my-app' when I run sudo systemctl status gunicorn
I realise something is being imported wrong or I do not have the correct directory listed in my gunicorn.service, but I'm struggling to figure out where the issue is regarding the [Service] part.
My /etc/systemd/system/gunicorn.service :
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=myname
Group=myname
EnvironmentFile=/home/myname/my-app/my-app/env
WorkingDirectory=/home/myname/my-app/my-app/app
ExecStart=/home/myname/env/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
my-app.app.wsgi:application
[Install]
WantedBy=multi-user.target
My directories are as follows:
./
./
env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/)
.bash_history
.bash_logout
.bashrc
.cache/
.cloud-locale-test.skip
.gitconfig
.local/
.profile
.ssh/
.sudo_as_admin_successful
.vim/
.viminfo
my-app/
|_ .DS_Store
|_ .git/
|_ .idea/
|_ .travis.yml
|_ Dockerfile
|_ docker-compose.yml
|_ env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/)
|_ requirements.txt
|_ my_app/
|_ .flake8
|_ db.sqlite3
|_ env
|_ manage.py*
|_ static/
|_ app/
|_ ./
|_./
|___init__.py
|___pycache__/
|_asgi.py
|_settings.py
|_urls.py
|_wsgi.py
Also, my settings.py since it might be relevant:
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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'seeecret'
# 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',
'app'
'my-app'
]
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 = 'app.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 = 'my-app.app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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/
STATIC_URL = '/static/'
Please could you help me with my EnvironmentFile, WorkingDirectory, ExecStart. Also, is my WSGI_APPLICATION = 'my-app.app.wsgi.application'or WSGI_APPLICATION = 'app.wsgi.application'? I feel like i've made this kind of mistake using the 2 interchangeably in many files, so pleas elet me know in which other files I would have to correct for this. Thank you so much in advance!
Everything looks good, you may be having a little confusion as to the structure of your WorkingDirectory and your ExecStart. In any case as you edit and test. Do in this order:
(1) sudo vi /etc/systemd/system/gunicorn.service
(2) sudo systemctl daemon-reload
(3) sudo systemctl restart gunicorn
(4) sudo systemctl status gunicorn
Related
I try to "dockerize" a Django project.
I've already dockerized a Django project ; I've tried to use the exactly same project architecture.
I have first config dev environnement.
I buil/run the 2 containers (web and db): OK.
I migrate: OK
When I try to collectstatic I got an error
FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/core/static'
and that right, static folder is at the same level as core app.
As I config dev environnement, with Django web server, I don't have to care about serving static files. So I've try to acces localhost:8000 and got an error:
That means I have an error in path config but I can find where as I replicate the same structure...
project architecture
- my_project
|_ app
|_ core
|_ wsqi.py
|_ settings
|_ base.py
|_ dev.py
|_ prod.py
|_ urls.py
|_ requirements
|_ base.txt
|_ dev.txt
|_ prod.txt
|_ static
|_ templates
|_ layout
|_ _footer.html
|_ _nav.html
|_ base.html
|_ home.html
|_ 404.html
|_ 500.html
|_ Dockerfile
|_ Dockerfile.prod
|_ entrypoint.sh
|_ entrypoint.prod.sh
|_ manage.py
|_ .dockerignore
|_ nginx
|_ .env.dev
|_ .env.prod
|_ .gitignore
|_ docker-compose.yml
|_ docker-compose.prod.yml
base.py
import os
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = int(os.environ.get("DEBUG", default=0))
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'widget_tweaks',
'bootstrap4',
'registration.apps.RegistrationConfig',
'monitor.apps.MonitorConfig',
'randomization.apps.RandomizationConfig',
'parameters.apps.ParametersConfig',
'unblind.apps.UnblindConfig',
'pharmacy.apps.PharmacyConfig',
'export.apps.ExportConfig',
'django_extensions',
'debug_toolbar',
'partial_date',
'safedelete',
'simple_history',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'randomization.middleware.stock',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'registration/templates'),
os.path.join(BASE_DIR,'monitor/templates'),
os.path.join(BASE_DIR,'randomization/templates'),
os.path.join(BASE_DIR,'unblind/templates'),
os.path.join(BASE_DIR,'pharmacy/templates'),
os.path.join(BASE_DIR,'export/templates'),
os.path.join(BASE_DIR,'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'randomization.context_processors.data_context_processor',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, 'db.sqlite3')),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
STATIC_URL = '/static/'
MEDIA_URL = "/media/"
INTERNAL_IPS = ['127.0.0.1']
LOGIN_URL = 'home'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
dev.py
from .base import *
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
os.path.join(BASE_DIR,'randomization/static'),
os.path.join(BASE_DIR,'unblind/static'),
os.path.join(BASE_DIR,'pharmacy/static'),
)
.env.dev
SECRET_KEY=*******************************
DEBUG=1
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
SQL_ENGINE=django.db.backends.postgresql
SQL_DATABASE=db_dev
SQL_USER=user
SQL_PASSWORD=user
SQL_HOST=db
SQL_PORT=5432
DATABASE=postgres
DJANGO_SETTINGS_MODULE=core.settings.dev
Dockerfile
# Pull the official base image
FROM python:3.8.3-alpine
# Set a work directory
WORKDIR /usr/src/app
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install psycopg2 dependencies
RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev
# J LE CARROU - 21/09/2020 - Ajouts
RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl
RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev
RUN pip3 install psycopg2 psycopg2-binary
# Install dependencies
COPY requirements/ requirements/
RUN pip install --upgrade pip && pip install -r requirements/dev.txt
# Copy the entrypoint.sh file
COPY ./entrypoint.sh .
# Copy the project's files
COPY . .
# Run entrypoint.sh
ENTRYPOINT [ "/usr/src/app/entrypoint.sh" ]
version: '3.7'
services:
web:
build: ./app
restart: always
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./app/:/usr/src/app
ports:
- 8000:8000
env_file:
- ./.env.dev
depends_on:
- db
db:
image: postgres:12.0-alpine
restart: always
volumes:
- postgres_data:/var/lib/postgres/data/
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=user
- POSTGRES_DB=db_dev
volumes:
postgres_data:
The BASE_DIR is referring to app/core, so you need to adjust the TEMPLATES directories as below:
'DIRS': [
os.path.join(BASE_DIR,'registration/templates'),
os.path.join(BASE_DIR,'monitor/templates'),
os.path.join(BASE_DIR,'randomization/templates'),
os.path.join(BASE_DIR,'unblind/templates'),
os.path.join(BASE_DIR,'pharmacy/templates'),
os.path.join(BASE_DIR,'export/templates'),
os.path.join(os.path.dirname(BASE_DIR,'templates')),
],
I am this error when I try to run my app on heroku. I have no idea what's causing it
ModuleNotFoundError: No module named 'deploytest.settings'
2020-05-15T21:02:25.372974+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-05-15T21:02:25.542793+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [4] [INFO] Shutting down: Master
2020-05-15T21:02:25.542795+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [4] [INFO] Reason: Worker failed to boot.
Procfile
web: gunicorn deploytest.deploytest.wsgi
I get the same error when my procfile is
web: gunicorn deploytest.wsgi
wsgi.py:
"""
WSGI config for deploytest project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'deploytest.settings')
application = get_wsgi_application()
settings.py
"""
Django settings for deploytest project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<key>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECURE_SSL_REDIRECT = True
SESSION_COOKIES_SECURE = True
ALLOWED_HOSTS = ['heroku']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'deploy.apps.DeployConfig',
]
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 = 'deploytest.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 = 'deploytest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/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.0/howto/static-files/
STATIC_URL = '/static/'
django_heroku.settings(locals())
my file structure is what you would expect of any typical django project. so settings.py and wsgi.py are both in the deploytest/deploytest directory. I have no idea what is causing this.
Update:
Putting my git inside deploytest/ did help out. I got the site working.
Try to deploy deploytest/ in such a way that you can see other apps too in root.
What I mean is do not upload this folder deploytest/deploytest
If you do not understand what I mean ask.
Then use this Procfile
web: gunicorn deploytest.wsgi --log-file -
I was able to get around this issue by using the --chdir flag for gunicorn inside of my Procfile.
So in this scenario I believe the following would work: web: gunicorn --chdir deploytest deploytest.wsgi
How to run gunicorn from a folder that is not the django project folder
I created a simple django & react app (which just loads react default page for now) and I am trying to deploy to Heroku. When I run python manage.py runserver on localhost it runs fine (with default react page showing), but when I deploy it to Heroku, I get the following error:
TemplateDoesNotExist at /
index.html
This is the site : https://temp-app-test.herokuapp.com/
I'm pretty sure I included index.html in templates using os.path.join(BASE_DIR, 'build') in settings.py, but it doesn't work. I also included "postinstall": "npm run build" in scripts in package.json file.
requirements.txt
asgiref==3.2.7
Django==3.0.6
pytz==2020.1
sqlparse==0.3.1
whitenoise==5.0.1
gunicorn==20.0.4
runtime.txt
python-3.7.4
Procfile
release: python manage.py migrate
web: gunicorn test_test_test.wsgi --log-file -
settings.py
"""
Django settings for test_test_test project.
Generated by 'django-admin startproject' using Django 2.2.10.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret'
# 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',
]
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 = 'test_test_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'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 = 'test_test_test.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
urls.py
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^.*', TemplateView.as_view(template_name='index.html'),
]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_test_test.settings')
application = get_wsgi_application()
I've been stuck here for hours, and I would like some help on this! Thanks in advance.
I am creating a docker image of a Django server that uses a postgresql database to keep track of login information, uploaded/downloaded files, etc. I want the data in my database to stick around even when I exit and relaunch the docker image.
I created a docker-compose file and entrypoint file that successfully launches the server docker image and creates a volume for the database. Every tutorial that I've read online has said that having persistent data is as simple as mapping your database volume from the location you want it stored on the host to the /var/lib/postgresql/data location in the docker image.
docker-compose.yml:
version: '3.7'
services:
web:
build: ./
command: python manage.py runserver 0.0.0.0:8000
ports:
- 8000:8000
environment:
- DEBUG=1
- SECRET_KEY=foo
- SQL_ENGINE=django.db.backends.postgresql
- SQL_HOST=db
- SQL_PORT=5432
- DATABASE=postgres
depends_on:
- db
db:
image: postgres
volumes:
- ./postgres_data:/var/lib/postgresql/data/
environment:
...
ports:
- 5432:5432
volumes:
postgres_data:
docker-entrypoint.sh:
#!/bin/sh
if [ "$DATABASE" = "postgres" ]
then
echo "Waiting for postgres..."
while ! nc -z $SQL_HOST $SQL_PORT; do
sleep 0.1
done
echo "PostgreSQL started"
fi
python manage.py flush --no-input
python manage.py migrate
exec $#
Dockerfile:
FROM python:3.7.4-alpine
ARG PROJECT=MyProject
ARG PROJECT_DIR=/var/www/${PROJECT}
RUN mkdir -p $PROJECT_DIR
WORKDIR $PROJECT_DIR
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN apk update \
&& apk add --virtual build-deps gcc python3-dev musl-dev \
&& apk add postgresql-dev \
&& pip install psycopg2 \
&& pip install django \
&& pip install djangorestframework \
&& pip install django-sslserver \
&& pip install djangosecure \
&& pip install psycopg2 \
&& pip install django-environ \
&& apk del build-deps
COPY . $PROJECT_DIR/
ENTRYPOINT ["/var/www/EchoNine/docker-entrypoint.sh"]
settings.py
import os
import sys
from django.conf import settings
import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MEDIA_URL = 'inspections/'
TEST_ROOT = os.path.join(BASE_DIR, 'test')
if ('test' in sys.argv):
MEDIA_ROOT = os.path.join(TEST_ROOT, 'inspections')
else:
MEDIA_ROOT = os.path.join(BASE_DIR, 'inspections')
root = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /)
environ.Env.read_env(env.str('ENV_PATH', '.env.production')) # reading .env fil
SECRET_KEY = env('SECRET_KEY')
DEBUG = env('DEBUG') # This is set to False
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangosecure',
'sslserver',
# Third-Party Apps
'rest_framework',
'rest_framework.authtoken',
# Local Apps (Your project's apps)
'MyProject.MyProject',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
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',
]
MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
ROOT_URLCONF = 'MyProject.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 = 'MyProject.wsgi.application'
DATABASES = {
'default': {
'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'),
'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')),
'USER': os.environ.get('SQL_USER', 'user'),
'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'),
'HOST': os.environ.get('SQL_HOST', 'localhost'),
'PORT': os.environ.get('SQL_PORT', '5432'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
STATIC_URL = '/static/'
When I launch the docker image, create a new super user inside the docker image (which stores data in the database), quit the docker image, and then relaunch the image, all database tables are empty again. I would expect the database to retain the database entries from the last run.
Both ./postgres_data on the host and /var/lib/postgresql/data inside the docker image seem to be initialized with files and a folder structure in them.
Can anyone tell me what I'm doing wrong? Thanks.
you delete everything by your Entrypoints since the entrypoint will start with every container operation (start/restart)
PS : manage.py flush will delete all your Data
I followed this tutorial here to setup Docker with Django. It works perfectly now and also my Postgres database seems to be installed. Where it fails for me is connecting with Postico (macOS) to my Postgres that's running in the container. Anyone who has experience in that, is it possible to connect 'from the outside' with eg. Postico to this container?
Currently I typed in:
Host localhost
User postgres
Password postgres
But I am not sure about the password, as in the tutorial I never set any.
docker-compose:
version: '3'
services:
db:
image: postgres
web:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
settings.py
"""
Django settings for composeexample project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 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 = 'XYZ'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = [
'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 = 'composeexample.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 = 'composeexample.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 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_URL = '/static/'
You said in comments:
I actually want to connect from my localhost, but not via terminal, but via Postico as I can easier edit database entries there.
If you wish to connect from localhost, you must expose the ports for pgsql.
version: '3'
services:
db:
image: postgres
expose:
- "5432"
ports:
- "5432:5432"
If you're on Linux, then you have to get your db IP with docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id and connect through the IP.
On Mac you can use localhost to access it.