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’ll install and configure PostgreSQL (often referred to as Postgres) with your Django application. You’ll also install some software packages, create database credentials for your application, and then start and configure a new Django project with this backend.
To get started, you will need an Ubuntu 22.04 server with a non-root user set up, 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.
First, update your package manager cache by using apt
:
- sudo apt update
Then, install essential components for your Django project. This includes pip
, the Python package manager, which installs and manages Python components. Additionally, install Postgres along with additional libraries to assist with your project:
- sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib
After installing Python, Postgres, and the additional libraries, you can move on to create your database.
By default, Postgres uses an authentication scheme called peer authentication for local connections. 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 postgres to perform administrative tasks. Use sudo
to pass in the username postgres
along with the -u
option which runs the command as a user, instead of root. Log into the interactive Postgres session by writing the following:
- sudo -u postgres psql
You can now access the shell session for the postgres
user.
Next, create a database for your Django project. Each project should have its own isolated database for security reasons. The database is called myproject
in this guide, but it is good practice to name it something more descriptive. Furthermore, when you’re entering in Postgres commands, remember to end the commands at an SQL prompt with a semicolon, ;
:
- CREATE DATABASE myproject;
Now create a database user that will connect to and interact with the database. Set the password to something strong and secure:
- CREATE USER myproject_user WITH PASSWORD 'myproject_database_password';
Afterwards, modify a few of the connection parameters for the user you 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. First, set the default encoding to UTF-8:
- ALTER ROLE myproject_user SET client_encoding TO 'utf8';
Then, set the default transaction isolation scheme to read committed
, which blocks reads from uncommitted transactions:
- ALTER ROLE myproject_user SET default_transaction_isolation TO 'read committed';
Lastly, set the timezone. By default, your Django project is set to use UTC
. These are recommendations from the Django project:
- ALTER ROLE myproject_user SET timezone TO 'UTC';
Now, give your database user access rights to the database you created:
- GRANT ALL PRIVILEGES ON DATABASE myproject TO myproject_user;
Exit the SQL prompt to get back to the postgres user’s shell session:
- \q
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.
You can get the virtualenv
package that allows you to create these environments entering the follow command:
- sudo pip install virtualenv
Next, create a directory to hold your Django project:
- mkdir ~/myproject
Then move into the directory:
- cd ~/myproject
Now you can create a virtual environment to store our Django project’s Python requirements with the following:
- python3 -m virtualenv myprojectenv
This installsa local copy of Python and pip
into a directory called myprojectenv
within your project directory.
Before installing applications within the virtual environment, you must activate it. You can do so by entering this command:
- source myprojectenv/bin/activate
Your prompt will change to indicate that you are now operating within the virtual environment. For example: (myprojectenv)user@host:~/myproject$
.
Once your virtual environment is active, you can install Django with pip
. You will also install the psycopg2
package that will allow you to use the database you configured:
- pip install Django psycopg2
Note: Regardless of the version of Python you are using, when the virtual environment is activated, you should use the pip
command instead of pip3
.
You can now start a Django project within your myproject
directory. This will create a child directory of the same name to hold the code, and will create a management script within the current directory. Make sure to include the dot .
at the end of the command so that this is set up correctly:
- django-admin startproject myproject .
With Django and your virtual environment set up, you can move on to configuring your 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 with your preferred text editor. nano
is used in this example:
- nano ~/myproject/myproject/settings.py
Towards the bottom of the file, there is a DATABASES
section that is currently configured to use SQLite:
. . .
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
. . .
This needs to be changed to use Postgres.
First, change the engine so that it uses the postgresql
adaptor instead of the sqlite3
backend. For the NAME
, use the name of your database. In this example, myproject
is the name of the database. Then add login credentials that include the username, password, and host to connect to. Lastly, leave the port option blank so that the default is selected:
. . .
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'myproject',
'USER': 'myproject_user',
'PASSWORD': 'myproject_database_password',
'HOST': 'localhost',
'PORT': '',
}
}
. . .
You also need to adjust the ALLOWED_HOSTS
directive. This defines a whitelist of addresses or domain names allowed to connect to the Django instance. Any incoming requests with a Host
header that are not in this list will raise an exception. Django requires that you set this to prevent a certain class of security vulnerability.
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 to request for an entire domain and any subdomains, prepend a period to the beginning of the entry.
You can add the domain name(s) and IP addresses of your Django server like so: ALLOWED_HOSTS = [ 'your_domain', '203.0.113.5']
. If you want to respond to your_domain
and any subdomains, start the domain with a dot .
: ALLOWED_HOSTS = ['.your_domain', '203.0.113.5']
.
For example, enter in your server domain or IP address:
. . .
ALLOWED_HOSTS = ['your_server_domain_or_IP']
. . .
When you are finished, save and close the file. If you’re using nano
, press CTRL+X
, then y
, then ENTER
.
Now that the Django settings are configured, you can migrate your data structures to your database and test out the server.
Begin by creating and applying migrations to your database. Since you don’t have any data yet, this will set up the initial database structure. First, make sure you’re in the myproject
directory:
- cd ~/myproject
Then make and apply the migration:
- python manage.py makemigrations
- python manage.py migrate
After creating the database structure, create an administrative account by entering the following:
- python manage.py createsuperuser
You will be asked to select a username. You can leave this blank to use the username associated with your server. Then provide an email address create a password for the account.
Before accessing the Django development server, test the connection to your database. Open the port in your firewall to allow external connections:
- sudo ufw allow 8000
Once you have the port open, you can test that your database is performing correctly by starting up the Django development server:
- python manage.py runserver 0.0.0.0:8000
In a web browser, visit your server’s domain name or IP address followed by :8000
to reach the default Django landing page:
http://server_domain_or_IP:8000
Append /admin
to the end of the URL and you should be able to access the login screen to the admin interface:
Enter the username and password you created using the createsuperuser
command. You will then be taken to the admin interface:
When you’re finished exploring, you can stop the development server by hitting CTRL+C
in your terminal window.
By accessing the admin interface, you have confirmed that your database has stored your user account information and that it can be appropriately accessed.
In this guide, you learned how to install and configure PostgreSQL as the backend database for a Django project. While SQLite can 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, read our guide on How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 22.04.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
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!