0% found this document useful (0 votes)
56 views16 pages

How To Use PostgreSQL With Your Django Application On Ubuntu 20.04 - DigitalOcean

Django tutorial

Uploaded by

TomDijkshoornn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views16 pages

How To Use PostgreSQL With Your Django Application On Ubuntu 20.04 - DigitalOcean

Django tutorial

Uploaded by

TomDijkshoornn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.

04 | DigitalOcean

CONTENTS
Prerequisites
Step 1 – Installing the Components from the Ubuntu Repositories
Step 2 – Creating a Database and Database User
Install Django within a Virtual Environment
Configure the Django Database Settings
Migrate the Database and Test your Project
Conclusion

// Tutorial //

How To Use PostgreSQL with your Django Application on

Ubuntu 20.04

Published on February 10, 2022


Django PostgreSQL Python Frameworks Ubuntu 20.04 Python Ubuntu

By Tony Tran and Justin Ellingwood

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 1/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Not using Ubuntu 20.04?


Choose a different version or distribution.
Ubuntu 20.04

Introduction

Django is a flexible framework for quickly creating Python applications. By default,


Django applications are configured to store data into a lightweight SQLite database file.
While this works well under some loads, a more traditional database management
system can improve performance in production.
In this guide, you will install and configure PostgreSQL (often referred to as Postgres) to
use with your Django applications. You will install the necessary software, create
database credentials for our application, and then start and configure a new Django
project to use this backend.
Prerequisites

You will need a clean Ubuntu 20.04 server instance with a non-root user
configured with sudo privileges. Learn how to set this up by following our initial
server setup guide.
When you are ready to continue, log in as your sudo user.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 2/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Step 1 – Installing the Components from the Ubuntu

Repositories

First you will install the essential components. This includes pip , the Python package
manager for installing and managing Python components, and also the database
software with its associated libraries.
You will be using Python 3, which ships with Ubuntu 20.04. Start the installation by
typing:
$ sudo apt update Copy
$ sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib

With the installation out of the way, you can move on to the database.
Step 2 – Creating a Database and Database User

By default, Postgres uses an authentication scheme called “peer authentication” for


local connections. Basically, this means that if the user’s operating system username
matches a valid Postgres username, that user can login with no further authentication.
During the Postgres installation, an operating system user named postgres was created
to correspond to the postgres PostgreSQL administrative user. You need to use this
user to perform administrative tasks. You can use sudo and pass in the username with
the -u option.
Log into an interactive Postgres session by typing:
$ sudo -u postgres psql Copy
First, you will create a database for the Django project. Each project should have its own
isolated database for security reasons. We will call the database myproject in this
guide, but it’s always better to select something more descriptive:
postgres=# CREATE DATABASE myproject ; Copy

note
Remember to end all commands at an SQL prompt with a semicolon.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 3/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Next, you will create a database user which you will use to connect to and interact with
the database. Set the password to something strong and secure:
postgres=# CREATE USER myprojectuser WITH PASSWORD ' password '; Copy
Afterwards, you will modify a few of the connection parameters for the user you just
created. This will speed up database operations so that the correct values do not have
to be queried and set each time a connection is established.
postgres=# ALTER ROLE myprojectuser SET client_encoding TO 'utf8'; Copy
postgres=# ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read commi
postgres=# ALTER ROLE myprojectuser SET timezone TO 'UTC';

You are setting the default encoding to UTF-8, which Django expects. You are also
setting the default transaction isolation scheme to “read committed”, which blocks reads
from uncommitted transactions. Lastly, you are setting the timezone. By default, your
Django projects will be set to use UTC . These are all recommendations from the Django
project itself.
Now, all you need to do is give your database user access rights to the database you
created:
postgres=# GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser ; Copy
Exit the SQL prompt to get back to the postgres user’s shell session:
postgres=# \q Copy

Install Django within a Virtual Environment

Now that your database is set up, you can install Django. For better flexibility, you will
install Django and all of its dependencies within a Python virtual environment. The
virtualenv package allows you to create these environments easily.

To install virtualenv , type:


$ sudo pip3 install virtualenv Copy
Make and move into a directory to hold your Django project:
$ mkdir ~/ myproject
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 4/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

$ cd ~/ myproject
Copy
You can create a virtual environment to store your Django project’s Python requirements
by typing:
$ python3 -m virtualenv myprojectenv Copy
This will install a local copy of Python and a local pip command into a directory called
myprojectenv within your project directory.

Before you install applications within the virtual environment, you need to activate it.
You can do so by typing:
$ source myprojectenv /bin/activate Copy
Your prompt will change to indicate that you are now operating within the virtual
environment. It will look something like this ( myprojectenv ) user @ host :~/ myproject $ .
Once your virtual environment is active, you can install the official release of Django with
pip . You will also install the psycopg2 package that will allow us to use the Postgres
database you configured:
Note
Regardless of which version of Python you are using, when the virtual environment is
activated, you should use the pip command (not pip3 ).

(myprojectenv) $ pip install Django psycopg2 Copy


You can now start a Django project within the myproject directory. This will create a
child directory of the same name to hold the code itself, and will create a management
script within the current directory. Make sure to add the dot at the end of the command
so that this is set up correctly:
(myprojectenv) $ django-admin startproject myproject . Copy

Configure the Django Database Settings

Now that you have a project, you need to configure it to use the database you created.
Open the main Django project settings file located within the child project directory:
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 5/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

(myprojectenv) $ nano ~/ myproject / myproject /settings.py Copy


Towards the bottom of the file, you will see a DATABASES section that looks like this:
~/myproject/myproject/settings.py
. . .

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

. . .

This is currently configured to use SQLite as a database. You need to change this so
that your PostgreSQL database is used instead.
First, change the engine so that it uses the postgresql adaptor instead of the sqlite3
adaptor. For the NAME , use the name of your database ( myproject in this example). You
also need to add login credentials. You need the username, password, and host to
connect to. You will add and leave blank the port option so that the default is selected:
~/myproject/myproject/settings.py
. . .

DATABASES = {
'default': {
'ENGINE': 'django.db.backends. postgresql ',
'NAME': ' myproject ',
'USER': ' myprojectuser ',
'PASSWORD': ' password ',
'HOST': 'localhost',
'PORT': '',
}
}

. . .

While
[New] Buildyou are here, you AI/ML
production-ready will also need to adjust
applicati… the ALLOWED_HOSTS
We're hiring Blog Docs directive.
Get SupportThisContact
definesSales
a whitelist of addresses or domain names allowed to connect to the Django instance.
Any incoming requests with a Host header that is not in this list will raise an exception.
Django requires that you set this to prevent a certain class of security vulnerability.
Tutorials Questions Learning Paths For Businesses Product Docs Social Impact
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 6/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

In the snippet below, there are a few commented out examples used to demonstrate:
~/myproject/myproject/settings.py
. . .
# The simplest case: just add the domain name(s) and IP addresses of your Django serv
# ALLOWED_HOSTS = [ 'example.com', '203.0.113.5']
# To respond to 'example.com' and any subdomains, start the domain with a dot
# ALLOWED_HOSTS = ['.example.com', '203.0.113.5']
ALLOWED_HOSTS = [' your_server_domain_or_IP ']

In the square brackets, list the IP addresses or domain names that are associated with
your Django server. Each item should be listed in quotations with entries separated by a
comma. If you wish requests for an entire domain and any subdomains, prepend a
period to the beginning of the entry.
When you are finished, save and close the file.
Migrate the Database and Test your Project

Now that the Django settings are configured, you can migrate your data structures to
your database and test out the server.
You can begin by creating and applying migrations to your database. Since you don’t
have any actual data yet, this will simply set up the initial database structure:
(myprojectenv) $ cd ~/ myproject Copy
(myprojectenv) $ python manage.py makemigrations
(myprojectenv) $ python manage.py migrate

After creating the database structure, you can create an administrative account by
typing:
(myprojectenv) $ python manage.py createsuperuser Copy
You will be asked to select a username, provide an email address, and choose and
confirm a password for the account.
If you followed the initial server setup guide, you should have a UFW firewall in place.
Before you can access the Django development server to test your database, you need
to open the port in your firewall.
Allow external connections to the port by typing:
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 7/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

(myprojectenv) $ sudo ufw allow 8000 Copy


Once you have the port open, you can test that your database is performing correctly by
starting up the Django development server:
(myprojectenv) $ python manage.py runserver 0.0.0.0:8000 Copy
In your web browser, visit your server’s domain name or IP address followed by :8000 to
reach default Django root page:
http:// server_domain_or_IP :8000

You should see the default index page:

Append /admin to the end of the URL and you should be able to access the login screen
to the admin interface:

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 8/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Enter the username and password you just created with the createsuperuser command.
You will then be taken to the admin interface:

When you’re done investigating, you can stop the development server by hitting CTRL-C
in your terminal window.
By accessing the admin interface, you have confirmed that you database has stored
your user account information and that it can be appropriately accessed.
Conclusion

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 9/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

In this guide, you have demonstrated how to install and configure PostgreSQL as the
backend database for a Django project. While SQLite can easily handle the load during
development and light production use, most projects benefit from implementing a more
full-featured database management system.
To take your project even further, see our guide on How To Set Up Django with
Postgres, Nginx, and Gunicorn on Ubuntu 20.04.

Thanks for learning with the DigitalOcean Community. Check out our offerings
for compute, storage, networking, and managed databases.
Learn more about us ->

About the authors

Tony Tran Author

Justin Ellingwood Author

Still looking for an answer? Ask a question


Search for more help

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 10/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Was this helpful? Yes No

Comments
1 Comments

Leave a comment...

This textbox defaults to using Markdown to format your answer.


You can type !ref in this text area to quickly search our full set of tutorials,
documentation & marketplace offerings and insert the link!
Sign In or Sign Up to Comment

[email protected] • February 11, 2022


This comment has been deleted

This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0


International License.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 11/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Sign up

Popular Topics

Ubuntu
Linux Basics
JavaScript
Python
MySQL
Docker
Kubernetes
All tutorials ->

Talk to an expert ->

Congratulations on unlocking the whale ambience easter egg! Click the whale button
in the bottom left of your screen to toggle some ambient whale noises while you
read.
Thank you to the Glacier Bay National Park & Preserve and Merrick079 for the
sounds behind this easter egg.
Interested in whales, protecting them, and their connection to helping prevent
climate change? We recommend checking out the Whale and Dolphin Conservation.
Reset easter egg to be discovered again / Permanently dismiss and hide easter egg

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 12/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Get our biweekly


newsletter

Sign up for Infrastructure as a


Newsletter.
Sign up ->

Hollie's Hub for Good

Working on improving health and


education, reducing inequality,
and spurring economic growth?
We’d like to help.
Learn more ->

Become a
contributor

You get paid; we donate to tech


nonprofits.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 13/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Learn more ->

Featured on Community

Kubernetes Course Learn Python 3 Machine Learning in Python


Getting started with Go Intro to Kubernetes

DigitalOcean Products

Cloudways Virtual Machines Managed Databases Managed Kubernetes


Block Storage Object Storage Marketplace VPC Load Balancers

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether
you’re running one virtual machine or ten thousand.
Learn more ->

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 14/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Get started for free

Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
Email address
Send My Promo
New accounts only. By submitting your email you agree to our Privacy Policy.

Company
Products
Community

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 15/16
05-08-2023 11:42 How To Use PostgreSQL with your Django Application on Ubuntu 20.04 | DigitalOcean

Solutions
Contact

© 2023 DigitalOcean, LLC.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-20-04 16/16

You might also like