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: sloriabgschiller Updated: 03/29/14
  • 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.utf8 -E utf8 -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 note for Homebrew users: The scripts added to your path by may conflict with your Homebrew installations. If this is a case, one quick fix is to add aliases that point to the binaries. For example: alias psql="/Applications/" 


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

Licensed under the CC-SA.