How to set up a PostgreSQL database in Django
You need to install psycopg2
Python library.
Installation
Download http://initd.org/psycopg/, then install it under Python PATH
After downloading, easily extract the tarball and:
$ python setup.py install
Or if you wish, install it by either easy_install or pip.
(I prefer to use pip over easy_install for no reason.)
$ easy_install psycopg2
$ pip install psycopg2
Configuration
in settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_user_password', 'HOST': '', 'PORT': 'db_port_number', }}
- Other installation instructions can be found at download page and install page.
Also make sure you have the PostgreSQL development package installed.On Ubuntu you need to do something like this:
$ sudo apt-get install libpq-dev
Step by step that I use:
- sudo apt-get install python-dev - sudo apt-get install postgresql-server-dev-9.1 - sudo apt-get install python-psycopg2 - Or sudo pip install psycopg2
You may want to install a graphic tool to manage your databases, for that you can do:
sudo apt-get install postgresql pgadmin4
After, you must change Postgre user password, then do:
- sudo su - su postgres -c psql postgres - ALTER USER postgres WITH PASSWORD 'YourPassWordHere'; - \q
On your settings.py file you do:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '', 'PORT': '', }}
Extra:
If you want to create the db using the command line you can just do:
- sudo su- su postgres -c psql postgres- CREATE DATABASE dbname;- CREATE USER djangouser WITH ENCRYPTED PASSWORD 'myPasswordHere';- GRANT ALL PRIVILEGES ON DATABASE dbname TO djangouser;
On your settings.py file you do:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'djangouser', 'PASSWORD': 'myPasswordHere', 'HOST': '', 'PORT': '', }}