Postgres is a database engine widely used, this time I'll show how to connect a Django project.
Using a database engine in an application is inevitable. In this tutorial we will learn how to connect to Postgres , engine relational database, with a project in Django .
requirements
To use Postgres as a database need some requirements.
$ Sudo apt-get install python-dev libpq-dev
We just need these two libraries to connect to Postgres with Django smoothly, once we have this we will install Postgres.
Installing Postgres
Installation is fairly simple.
$ Sudo apt-get install postgresql
With this Postgres will install and start running the service, once the installation is complete we will assign a password to that user.
$ Passwd postgres
Add a password when prompted. Now we can enter that user.
$ Your postgres
You give the password you assigned a moment ago and that the user already entered Postgres.
Creating a Database
When you are already in Postgres user and can begin to create what we need are 3 things, a database, a user of the database, and assign a password to that user database.
$ Createdb Ejemplo_BD
$ Createuser Ejemplo_Usuario
$ psql
= ALTER USER Ejemplo_Usuario WITH PASSWORD 'password_usuario' ;
With the first line we create a database with the name "Ejemplo_DB" , with the following line to create the user "Ejemplo_Usuario" , with the next line we enter the interactive shell Postgres to assign a password to our user, in this case it is"password_usuario" . These 3 data are necessary for the connection, so remember them that later we will use them .
psycopg2
To connect with any database engine always need a connector, in this case to connect to Postgres with psycopg2 use Python, so let's install it.
$ Pip install psycopg2
This is to be installed in your virtual environment (I hope you are using), now let the project settings in Django.
Configuring Django
To configure Django let's edit the configuration file that are using or the settings.pyif you are not using multiple settings (they should).
DATABASES = {
'default' : {
'ENGINE' : 'django.db.backends.postgresql_psycopg2' ,
'NAME' : 'Ejemplo_DB' ,
'USER' : 'Ejemplo_Usuario' ,
'PASSWORD' : 'password_usuario' ,
'HOST' : 'localhost' ,
'PORT' : '5432' ,
}
}
In this variable in the configuration file must put the data we previously created in "NAME " is the name of the database, " USER " the user name of the database and password, the password for that user, the rest are variables that never change, "eNGINE " the engine that will use so we pass the psycopg2 connector, the HOSTand PORT put localhost and 5432 respectively.
As you saw with Django connect to Postgres it is relatively simple, remember that we have a course of Django and Fundamentals of Django where you will learn from scratch to develop this framework.