[Quicknotes] Setup Postgres in Django

Hey! These are my quick rough notes (point to point without my round around blabberings) on “How to Setup Postgres Database in Django”. Hope it would help someone!

  1. Have the base django setup (of course)
  2. Install Postgres locally ūüėČ
  3. Activate your project virtual env
  4. pip install psycopg2-binary  a more stand alone package than psycopg2. Find out more here.
  5. pip install django-environ if you want to get your db configs from .env file
  6. Don’t forget to add these packages in your¬†requirements.txt ūüôā
  7. In your settings.py replace (with caution!) the DATABASES dictionary with the following statements:
    1. DATABASES = {"default": env.db("DATABASE_URL", default="postgis://localhost/<project-name>")}
    2. DATABASES["default"]["ENGINE"] = "django.db.backends.postgresql_psycopg2
    3. NOTE: as we are using env.db you must import environ and initiate the env object in the same file like follows:
      1. import environ
      2. env = environ.Env()
  8. Create a PG database on your local machine createdb <project-name>
  9. And you are good to go with running your django migrate
  10. In case you create password protected PG database on your machine or the username of that PG database is someone else, then because we have used django-environ , therefore you may write a .env file in your project root and write the following in it.
    1. DATABASE_URL=postgres://username:password@yourhost.com:5432/database_name and again that 5432 is a default postgres port (configurable though)
    2. NOTE: but make sure that .env file should be available to environ. To make it visible you may use something like:
      1. environ.Env.read_env(env_file='<path/to/.env_dir/.env>')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s