All I want to do is. . .

. . .use PostgreSQL with Flask or Django.


A quick guide to get started using Postgres with a Flask or Django app.
Contributors: sloriabgschillertristaneuanTayHobbs Updated: 01/17/15
  • Updated 2015-01-17: Update paths to psql binary in Thanks @TayHobbs.
  • Updated 2014-05-18: Fix createdb listing. Thanks @trastaneuan. Also fixed the footnote re: adding's binaries to $PATH.
  • Updated 2014-03-29: Fix createuser and createdb commands. Thanks @bgshiller.

Install Postgres

First, download and install Postgres for your OS here.

Sidenote for MacOSX users: I have found to be the simplest option1. Just download and run the app.

# check that you successfully installed postgres
$ which psql

Create a new user and a database

# Create a new user
$ sudo -u postgres createuser -s $USER
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases (y/n) y
Shall the new role be allowed to create more new roles? (y/n) n

# Create a new database
$ createdb -U $USER --locale=en_US.utf-8 -E utf-8 -O $USER yournewdb -T template0

Set up Postgres with Flask or Django

# install psycopg2
$ pip install -U psycopg2
# If using SQLAlchemy
$ pip install Flask-SQLAlchemy


# Flask
SQLALCHEMY_DATABASE_URI = "postgresql://yourusername:yourpassword@localhost/yournewdb"
# Flask
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)


# Django
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'yournewdb',
        'USER': 'yourusername',
        'PASSWORD': 'yourpassword',
        'HOST': 'localhost',
        'PORT': '5432',

That's it! Go ahead and write your models.

See also:

For viewing/managing your databases:

  1. IMPORTANT: If you use, make sure to add its binaries directory to your path. You can do so by adding export PATH="/Applications/$PATH" to your .bashrc (or .zshrc, .bash_profile, etc.) 


If you have suggestions, corrections, or content to contribute, fork us at our Github repo or open an issue.

Licensed under the CC-SA.