How to use PostgreSQL with Django _ EDB
How to use PostgreSQL with Django _ EDB
Postgres Tutorials
Back
This article covers how to use PostgreSQL together with the Python web application framework
Django. After walking through the Django installation process it shows how to get started
creating a simple Django application.
1. Getting started
3. Installing Django
In the early days of web development, the framework of choice was LAMP, or
Linux+Apache+MySQL+PHP. While PHP is still a great language for coding, Python has picked up a lot
of popularity. With its clean syntax and use in a variety of industries, Python becomes a natural choice
for any budding coder. In this article, we’ll show you how to get Postgres connected with Django, a
popular web application framework for Python.
Getting started
When working with Python, it’s highly recommended to use a virtual environment. This prevents
dependency collisions and undesired behaviors that would otherwise arise from premature or
unintended version changes. As such, we highly encourage you to use “virtualenv,” along with Python
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 1/13
7/7/2020 How to use PostgreSQL with Django | EDB
v. 3.x. Obtaining and installing Python v. 3.x is a task outside the scope of this article, but there are
many resources out there that provide instructions on how to do this.
We will also assume that you’ve got a Postgres instance up and running somewhere. If you need help
with that, we’ve got articles that you can refer to.
mkdir /var/myproject
cd /var/myproject
Then, you will need to use “virtualenv” to create a place for the environment-specific dependencies to
be installed:
Python 2.7.5
Python 3.6.3
To get Python working with Postgres, you will need to install the “psycopg2” module. However, you
must first have pg_config installed on your OS:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 2/13
7/7/2020 How to use PostgreSQL with Django | EDB
/usr/pgsql-12/bin/pg_config
If you can’t find pg_config on your OS, you will need to install a Postgres client first. After you ensure
pg_config is available on your system, go ahead and install “psycopg2”:
Installing Django
Once we’ve activated the virtual environment, we can install Django into that environment, so as to
keep things in your project from interfering with the host OS:
Once Django has been installed, you can start a new Django project:
/var/myproject/myprojectenv/bin
By default, Django is configured to use SQLite as its backend. To use Postgres instead,
“myproject/settings.py” needs to be updated:
# cat myproject/settings.py
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': ‘<db_name>’,
'USER': '<db_username>',
'PASSWORD': '<password>',
'HOST': '<db_hostname_or_ip>',
'PORT': '<db_port>',
. . .
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 3/13
7/7/2020 How to use PostgreSQL with Django | EDB
Once you’ve got things pointed to the Postgres database, you can build the default schema. If you
didn’t know already, Django was designed with user access in mind, so by default a Django application
will create a database schema involving users, groups, and permissions. To create the schema,
generate a migration and run it:
No changes detected
Operations to perform:
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
Password:
Password (again):
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 4/13
7/7/2020 How to use PostgreSQL with Django | EDB
Now, the moment of truth! Start the application up, and point your browser to the corresponding port:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 5/13
7/7/2020 How to use PostgreSQL with Django | EDB
Let’s make the app display a relationship between cars and their owners:
This creates a folder called “cars”, which consists of the following important files:
total 24
Let’s tell the framework what a Car and a Driver look like, by defining them in “models.py”:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 6/13
7/7/2020 How to use PostgreSQL with Django | EDB
class Driver(models.Model):
name = models.TextField()
license = models.TextField()
class Car(models.Model):
make = models.TextField()
model = models.TextField()
year = models.IntegerField()
vin = models.TextField()
Then, make the migration to build the tables in the database, and run it:
cars/migrations/0001_initial.py
Operations to perform:
Running migrations:
Applying cars.0001_initial... OK
Take a look in the database, and you’ll see that the table has been created with the format
“<project_name>_<object_name>”:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 7/13
7/7/2020 How to use PostgreSQL with Django | EDB
postgres=# \d
List of relations
--------+-----------------------------+----------+----------
<...>
I also created some random data for the purposes of this tutorial:
id | name | license
----+----------+----------
(2 rows)
----+--------+--------+------+----------------------------------+----------
(4 rows)
We need to tell Django how to pull stuff out of the database and display it. By editing the
“cars/views.py” file, we can accomplish this:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 8/13
7/7/2020 How to use PostgreSQL with Django | EDB
owner_obj = Driver.objects.get(pk=pk)
car_objs = Car.objects.filter(owner_id=owner_obj.id)
context = {
"vehicles": car_objs,
"drivers": owner_obj,
We also need to define a template so that the “views.py” procedures have a place to send the data.
First, we create a “cars/template/base.html” file that contains the more generic elements of an HTML
page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contacts</title>
<link rel="stylesheet"
href="https://unpkg.com/tachyons@4.10.0/css/tachyons.min.css"/>
</head>
<body>
</body>
</html>
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 9/13
7/7/2020 How to use PostgreSQL with Django | EDB
{% extends "base.html" %}
{% block page_content %}
{% for v in vehicles %}
<div class="pl2">
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Finally, we need to tell the webserver how to route the traffic. First, in “cars/urls.py”, we define how
the REST behavior works:
urlpatterns = [
Note that this will allow us to retrieve Car and Driver objects based on the ID provided in the URL.
Then, in “myproject/urls.py,” we define the root URL for the “cars” application:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 10/13
7/7/2020 How to use PostgreSQL with Django | EDB
urlpatterns = [
path('admin/', admin.site.urls),
path("cars/", include("cars.urls")),
Tell Django that the “cars” app is active by adding “cars” to the “INSTALLED_APPS” list in
“myproject/settings.py”:
Change the “1” to a “2” in the URL, and we will get the Driver with `id=2` and the Cars owned by that
Driver:
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 11/13
7/7/2020 How to use PostgreSQL with Django | EDB
This is a very simple example of how Django can be used to serve up web pages with data from
PostgreSQL. More information about how to define relationships between Django and PostgreSQL
(many-to-many relationships, complex joins, complex filtering, etc.) can be found at the Django
documentation.
Why EDB?
Use Cases
Oracle Migration
Hybrid Cloud
High Availability
Solutions for
IT Professionals
Database Architects
Developers
Database Admins
Products
Databases
EDB Postgres Advanced Server
PostgreSQL
Tools
Postgres Enterprise Manager
Failover Manager
Migration Portal
Migration Toolkit
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 12/13
7/7/2020 How to use PostgreSQL with Django | EDB
Migration Toolkit
Replication Server
Services
Services Overview
Getting Started
Postgres Optimization
Enterprise Strategy
Custom Services
Support
Customer Support Portal
Support Overview
Resources
Downloads
Blog
Webinars
PostgreSQL Tutorials
Training
Partners
White Papers
Case Studies
Docs
Plans
Company
About EDB
PostgreSQL Contributions
Careers
Events
Press Releases
Media Coverage
Customers
Follow Us
Twitter
YouTube
https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django 13/13