Django is a powerful free and open-source Python web framework designed for security, scalability, reusability, and rapid development. Initially released in 2005, Django is tried and tested for developing both simple prototypes as well as large-scale projects. The framework encourages clean, pragmatic design, and provides developers with a comprehensive set of tools to build scalable dynamic web applications (DWAs).
Hire the best developers in Latin America. Get a free quote today!
Contact Us Today!A dynamic web application is an application that can change its appearance, content, and functionality in response to user input, system events, and information. Dynamic web applications are reliant on databases for persisting content. Django, being a modern framework, supports several standard database programs, for example, SQLite, Marinade, MySQL, PostgreSQL, Oracle, MongoDB, etc.
In this guide, you will learn how to create a Django web application, and connect it to a PostgreSQL database. PostgreSQL is one of the most advanced and widely used Database Management Systems for Django. This practical guide is intended to help developers get up and running with Django development.
Why Latin American Developers Prefer Django
Latin American developers often prefer Django for its robustness and efficiency, making it a top choice for nearshore software development projects in South America.
This Python-based framework is renowned for its pragmatic design and rapid development capabilities, which align perfectly with the agile and innovative nature of tech talent in this region. By opting for Django, businesses looking to hire developers in Latin America can leverage the framework’s scalability and security features. This synergy between Django’s capabilities and the expertise of Latin American developers fosters a productive environment for dynamic web applications, positioning Latin America as an attractive nearshore destination for global tech projects.
Prerequisites
To follow along, you will need to satisfy the following requirements:
- This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have a Linux-based system with a non-root sudo-enabled user – This tutorial uses Ubuntu 20.04 LTS, but other distros will also work.
- Basic knowledge of Python is required.
Steps
Step 1 — Install and Configure Python 3
Being a Python web framework, Django requires Python. Python is a powerful, high-level scripting language that is ideal for web development. Your Ubuntu distribution ships with Python already pre-installed by default. For this guide, you’ll be using Python 3. Installing Python on Ubuntu is fairly easy:
1. Open up your terminal by pressing Ctrl + Alt + T
2. First, update your local system’s APT
cache and upgrade (if available) all the installed packages:
$ sudo apt update && sudo apt upgrade -y
3. Python 3
is directly available from the official Ubuntu package repositories. Download the latest version of the Python package alongside the python-is-python3
binary that creates a soft link to python3
for ease of use:
$ sudo apt install python3 python-is-python3
APT
will automatically retrieve the package and install it on your workstation.
4. Next, verify if the installation was successful:
$ python3 --version
You should see an output similar to this:
Python 3.x.y (main, Aug 03 2022, 21:55:17)
[GCC 9.x.y] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
5. Finally, you need to install some essential packages to set up a robust programming environment:
$ sudo apt install build-essential libssl-dev libpq-dev libffi-dev python3-dev
Step 2 — Install PostgreSQL
PostgreSQL is a free and open source relational database management system (RDBMS) that provides an implementation of the SQL querying language.
1. To install the PostgreSQL database software alongside the -contrib package that adds some additional utilities and functionality, run the following command:
$ sudo apt install postgresql postgresql-contrib
2. If the installation was successful, then PostgreSQL will start running in the background. Verify that the service is working properly:
$ sudo systemctl start postgresql.service
With the PostgreSQL server up and running, you can now safely transition to setting up your database.
Step 3 — Configure PostgreSQL
The installation procedure created a user account called postgres
that is associated with the default PostgreSQL administrative user. Let’s utilize this account to perform some administrative tasks.
1. First, run the following command to switch to the postgres
user and open the psql
command-line interface for working with PostgreSQL.
$ sudo -u postgres psql
This will log you into an interactive PostgreSQL session.
2. Once you’re logged into PostgreSQL, the next step is to create a database for your Django app. In this case, let’s call it usersDB
.
CREATE DATABASE usersDB;
3. Run the following query to create a new user called sammy
. You can replace sammy
with a name of your choice.
CREATE USER sammy WITH PASSWORD 'pa$$word';
4. Now, run the following query to give your user (sammy
) full access to the usersDB
database, including creating new tables and documents.
GRANT ALL PRIVILEGES ON DATABASE usersDB TO sammy;
5. Next, modify a few of the connection settings for your user to speed up database operations.
ALTER ROLE sammy SET client_encoding TO 'utf8';
ALTER ROLE sammy SET default_transaction_isolation TO 'read committed';
ALTER ROLE sammy SET timezone TO 'UTC';
6. Finally, exit the SQL prompt using the following command:
\q
With the database configured, it’s now time to set up your development environment.
Step 4 — Create a Virtual Environment
A virtual environment provides an isolated Python development environment. This means that the Python libraries, interpreter, and scripts installed into the virtual environment are isolated from those installed system wide or in any other virtual environment. This is a common approach that is used in complex software development projects where often you will be working with multiple files, packages, and dependencies. You will use the venv
module to create a lightweight virtual environment. To get started:
1. Navigate to the directory where you would like to build your Django app. Inside that directory, create a specific project directory to build the application. Let us name it “django-projects
”.
$ mkdir django-projects
2. Next, navigate to the django-projects
directory.
$ cd django-projects
3. Let’s use the venv
tool to create a virtual environment called env
is your virtual environment name. You can name whatever name you want but it is recommended to use a name that is meaningful and consistent with the application you’re building.
$ python3 -m venv env
4. The last step is activating your virtual environment. Run the activate
script located in the virtual environment’s executables directory using the following command to activate it:
$ . env/bin/activate
Now you have a Python virtual environment that can isolate your Python development environment from your system installed Python as well as other Python environments.
Step 5 — Install Django
After creating the directory and virtual environment for your Django project, it’s now time to install Django. You will be installing Django inside your dedicated virtual environment.
1. Use the PIP
package manager to download and install Django:
$ pip install django
If the command is successful, the latest version of Django will be automatically installed in your environment.
2. Verify that Django was installed by typing python
in your shell. At the interactive Python prompt, try to import Django:
>>> import django
>>> print(django.get_version())
4.0
Note that the output may display a different version of Django. With Django already installed, you’re all set — it’s time to generate a Django project.
Step 6 — Generate a Django Project
Now that you have installed Django, it’s time to create your first project. You will use the django-admin
tool to create a new Django project.
$ django-admin startproject djangoPostgres
This command will generate a project folder called djangoPostgres
, the basic file templates, and manage.py
— your project management script. Your project folder should have the following tree structure:
djangoPostgres/
manage.py
djangoPostgres/
__init__.py
settings.py
urls.py
wsgi.py
asgi.py
Your current working directory should look similar to this:
../django-projects/djangoPostgres/
- djangoPostgres: This sub-folder serves as the entry point to your application.
- manage.py: This script is used to create applications, work with databases, and start the development web server.
- __init__.py: This is an empty file that tells Python to treat the djangoPostgres subdirectory as a Python package.
- settings.py: This file contains all your application’s settings, including registering any applications that you are going to create, the location of our static files, database configuration details, etc.
- urls.py: This file defines the URL mapping code.
- wsgi.py: This file is used to help your Django application communicate with the webserver.
- asgi.py: Used as an entry-point for ASGI-compatible web servers to serve your Django application.
Now that you’ve created a project directory containing the initial start of your application, you can move on to the next step.
Step 7 — Start a Django App
1. Inside your project folder (../django-projects/djangoPostgres/
), run the following command to start your first app:
$ python manage.py startapp users
2. Next, run the server to check that everything is okay:
$ python manage.py runserver
After building the app, it’s now time to set up your database.
Step 8 — Configure the Database Connection
Django provides an easy way to switch from the default SQLite database to a production-ready DB Engine like PostgreSQL using a generic interface. The database settings are saved in the settings.py
file located within the project directory. You need to change a few of the default settings in this file to get everything working correctly.
To edit the file:
1. Open the path to your file and run the following command:
$ nano settings.py
2. Near line 76 of the code, you will find the database config section. This is the default SQLite
database configuration that Django provides.
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
. . .
You can instantly connect Django to a SQLite
database using this configuration without having to install any additional package. This is because SQLite
stores data into a single file. Therefore, no server is required which is ideal for development or small applications. But we want a professional database so let’s change some settings.
Copy and paste the code below to the settings.py
file and save.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'usersDB',
'USER': 'sammy',
'PASSWORD': 'pa$$word',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Reference:
- NAME → Database name e.g. usersDB that you created earlier in Step 3
- USER → Database username e.g. sammy
- PASSWORD → Database password
- HOST → Database host (In the development stage, use 127.0.0.1)
- PORT → The port that used to run the database (The default port is 5432)
Step 9 — Create a Database Table
Let’s now create a simple table to test things out. You can create a table by directly writing a class/object(ORM) to access the database instead of writing raw SQL.
Open the users/models.py file and create a simple model for testing that defines a Person, with a first_name and last_name. It should look similar to this:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
Step 10 — Migrate the Table to PostgreSQL Database
At this point, you have successfully defined your table. However, the table hasn’t been sent to PostgreSQL yet. So what do you need to do for your changes to reflect in your database?
1. First, you need to install the Psycopg
Python library. Psycopg
is a popular PostgreSQL adapter that facilitates communication between Django and PostgreSQL. You can install Psycopg
by running the following command:
$ pip install psycopg[binary]
2. Next, go to settings.py and register your app so that it can be included when any tools are run, for example, adding models to the database. Django applications are registered by adding them to the INSTALLED_APPS list in settings.py. Open the file and add your:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add your new application
'users.apps.UsersConfig', #This object was created for us in /users/apps.py
]
3. The new line specifies the application configuration object (UsersConfig) that was generated for you in /djangoPostgres/users/apps.py
when you first created the application.
4. After registering your application, run the makemigrations command to update the changes in your models.py e.g. adding a new table, changing a field name, etc.
$ python manage.py makemigrations
5. The final step is running the migrate command which will send your table to the database.
$ python manage.py migrate
Congratulations! You have successfully created a Django application and connected it to a PostgreSQL database.
Conclusion
So just to recap, in this guide you have learned how to:
- Install and configure Python
- Install and configure a PostgreSQL database
- Create a development environment for your project
- Build a Django application
- Write a database table using Django ORM without touching any SQL syntax.
With this foundation, you can begin developing Django applications. If this guide is helpful, please do not hesitate to drop your comment below sharing with us your opinion or recommendation.
Ready to elevate your project with top-tier talent? Contact us today to hire the best Latin American developers and experience the unmatched efficiency of nearshore South American software solutions. Whether it’s Django development, Artificial Intelligence or custom IT services, our dedicated team is prepared to bring your vision to fruition. Get your free quote now and join the ranks of satisfied clients who have successfully transformed their businesses with our expert nearshore staffing solutions.