Requirements
- VirtualEnv
- Django
- PostgreSQL
Add on to post from Painless PostgreSQL + Django
The recommendation is to follow the steps from the original well-written post and refers to the following to fill in some of the possible gaps .
- Activate a virtualenv
- Git clone the project (in the post) to local directory
- Run pip install -r requirements.txt
- Upgrade Django version (will encounter error if this step is not performed). pip install django==1.11.17. This only applies if you following the post and cloning the project used in the post.
- Create new user in Postgres, create new database & grant assess (Step 1 & 2 of post)
- Update settings.py on the database portion.
- Create environment variables in the virtualenv. See link for more information.
- Note: Secret Key needs to be included as one of the environment variable.
- Update the postactivate file of the virtualenv so the environment variables are present when virtualenv is activated.
- To get path of the virtualenv: echo $VIRTUAL_ENV
Create new user in Postgres
# Psql codes for Step 1 and 2 of original post. # ensure Postgres server is running psql # create user with password CREATE USER sample_user WITH PASSWORD 'sample_password'; # create database CREATE DATABASE sample_database WITH OWNER sample_user;
Update database information in Setting.py
# Changes in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USER', ''), 'PASSWORD': os.environ.get('DB_PASS', ''), 'HOST': 'localhost', 'PORT': '5432', } # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '')
Update environment variables in VirtualEnv
# postactivate script in the project virtual env bin path. # E.g. ~/.virtualenv/[projectname]/bin/postactivate #!/bin/bash # This hook is sourced after this virtualenv is activated. export DB_NAME='sample_database' export DB_USER='sample_user' export DB_PASS='sample_password' export DJANGO_SECRET_KEY='thisissecretkey'
Running migrations (Ensure PostgreSQL server is running)
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py runserver
Additional notes:
- When running python manage.py runserver on local host and error occurs, check domain is included in the ALLOWED_HOSTS of setting.py. Alternatively, you can use below:
- ALLOWED_HOSTS = [‘*’] # for local host only
- No database created when running psql command: CREATE DATABASE …, check if semi-colon add to end of the statement. In the event, the ‘;’ is missing, type ‘;’ and try inputting the commands again. See link for more details.