This is a short guide for common database setup for a django app using DJ-Database-URL. This is focused on setting up a development environment. Production will be similar but instead of using the default DB location and credentials, you should use the location of the actual DB server and you really ought to be using a secret password.
The simplest is to use the default database connection parameters, but you can override them in your development environment.
Look in the project settings file. For a project called publicpeople, you'd probably
find the database settings in publicpeople/settings.py
around a set of config code
like the following:
import dj_database_url
db_config = dj_database_url.config(default='postgres://publicpeople@localhost/publicpeople')
db_config['ATOMIC_REQUESTS'] = True
DATABASES = {
'default': db_config,
}
In this case, the database connection details are the URL in the default
argument to the
dj_database_url.config
function call.
That URL means:
- username:
publicpeople
- password: none
- database hostname:
localhost
- database name:
publicpeople
If the URL has a colon and something before the @, the password is that something, e.g.
in postgres://publicpeople:somepassword@localhost/publicpeople
the password is somepassword
If you want to use your own custom DB credentials (e.g. in production, or because you want to use a different database name in development), run all django commands (once you've created the database and user) that need the database with the environment variable DATABASE_URL
, e.g.
DATABASE_URL=postgres://username:somepassword@172.0.0.2/dbname python manage.py runserver
or
export DATABASE_URL=postgres://username:somepassword@172.0.0.2/dbname
python python manage.py migrate
You can create roles and databases within psql (postgres command line client) or using postgres command line programs.
Connect to the database as a postgres admin user, e.g.
sudo su postgres
[sudo] password for fakeuser:
[postgres@fakehost public-people]$ psql
psql (10.3)
Type "help" for help.
postgres=#
Then create the role
postgres=# create role publicpeople with login password 'somepassword' ;
Allow superusername to make the role owne the new db
postgres=# grant publicpeople to superusername
And finally create the database
postgres=# create database publicpeople with owner publicpeople;
See createuser
and createdb
at https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb#a2-the-createuser-utility
Hi @jbothma thanks for sharing this guide. I wondered if you had any experince using dj_database_url with multiple databases? I'm looking to set up something similar to this