1. Deactivate the virtualenv if there is.
pyenv deactivate
2. Install the required libraries.
sudo apt-get install libpq-dev python-dev
3. Install PostgreSQL.
sudo apt-get install postgresql postgresql-contrib
4. Start the psql shell.
sudo -u postgres psql
5. Setup the postgres user password by entering the following command and you will be prompted for password in the psql shell. Press Control + D to quit after it is done.
\password postgres
6. Create a new database user called django_user.
sudo -u postgres createuser django_user
7. Go to the psql shell again.
sudo -u postgres psql
8. Create the database and name it django_db.
createdb django_db
9. Set the password for django_user.
ALTER USER django_user WITH PASSWORD '<password>';
11. Grant the privilege properly.
GRANT ALL PRIVILEGES ON DATABASE django_db TO django_user;
12. Exit the psql shell and activate the virtualenv.
pyenv activate <virtualenv>
13. Install the psycopg2 package.
pip install psycopg2
14. Edit the Django project settings.py as follow.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_db', 'USER': 'django_user', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '5432', } }
15. Initialize the db.
python manage.py syncdb
16. Start the Django project and see if everything works fine.
python manage.py runserver 0.0.0.0:8000
Done =)
- Digital Ocean – How To Install and Configure Django with Postgres, Nginx, and Gunicorn
- Ubuntu documentation – PostgreSQL
- Kill The Yak | use PostgreSQL with Flask or Django.
- StackOverflow – Createuser: could not connect to database postgres: FATAL: role “tom” does not exist
Filed under: Database, Django Tagged: Django, PostgreSQL, pyenv, Python, Ubuntu, virtualenv