Using Postgresql With Django


Before using PostgreSQL with Django, you need to create a database and database user. Please refer to following for creation of database and user using terminal. ```sql $sudo su - postgres [sudo] password for USER: postgres@inspiron-3542:~$ psql postgres=# postgres=# CREATE DATABASE polls; postgres=# CREATE USER pollsuser WITH PASSWORD 'password'; CREATE ROLE postgres=# ALTER ROLE pollsuser SET client_encoding TO 'utf8'; ALTER ROLE postgres=# ALTER ROLE pollsuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE postgres=# ALTER ROLE pollsuser SET timezone TO 'Asia/Kolkata'; ALTER ROLE postgres=# GRANT ALL PRIVILEGES ON DATABASE polls TO pollsuser; GRANT postgres=# \q ``` You can set timezone to "UTC" or "CET" as per your requirement. Now, make following changes in settings.py. be default Django use SQLLITE3, you simple need to comment these two lines and add new lines to provide details about database host, port, database name, user, password. here, host need not be localhost always, you can provide external database server names but you need to ensure, there is connectivity established between database server and application server. ```python DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'polls', 'USER': 'pollsuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } ``` This is because we have not created polls database. Now let us run makemigrations. makemigrations is like version control for database. ```bash python3 manage.py makemigrations python3 manage.py migrate ``` Once you have created database, please do not forget to create superuser using following command ```python python3 manage.py createsuperuser ``` and you are all set.

This post is written by Pravin

Tags : Python Django PostgreSQL

Share it :      

Leave a comment

captcha