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).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.
Prerequisites
To follow along, you will need to satisfy the following requirements:1. 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.
2. 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:
4. Next, verify if the installation was successful:
You should see an output similar to this:
[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:
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:
2. If the installation was successful, then PostgreSQL will start running in the background. Verify that the service is working properly:
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.
3. Run the following query to create a new user called sammy. You can replace sammy with a name of your choice.
4. Now, run the following query to give your user (sammy) full access to the usersDB database, including creating new tables and documents.
5. Next, modify a few of the connection settings for your user to speed up database operations.
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:
Allow remote access
In this step, we will look at how to configure Postgres to accept external connections. To begin, open the configuration file with your preferred editor:
# nano /etc/postgresql/10/main/postgresql.conf
Look for this line in the file:
#listen_addresses = 'localhost'
Uncomment, and change the value to '*'
, this will allow Postgres connections from anyone.
listen_addresses = '*'
Save and exit the file. Next, modify pg_hba.conf
to also allow connections from everyone. Open the file with your preferred editor:
# nano /etc/postgresql/10/main/pg_hba.conf
Modify this section:
# IPv4 local connections:
host all all 127.0.0.1/32 md5
To this:
# IPv4 local connections:
host all all 0.0.0.0/0 md5
This file stores the client authentication, each record specifies an
IP address range, database name, username, and authentication method. In
our case, we are granting all database users access to all databases
with any IP address range, thus, letting any IP address connect. Save
and exit the file. Next, allow port 5432
through the firewall by executing:
sudo ufw allow 5432/tcp
Finally, restart Postgres to apply all the changes you have made to its configuration by running:
sudo systemctl restart postgresql
Connect to Postgres remotely
In this step, you will be connecting to your server from an external machine. Connect to the remote Postgres database by running:
psql -h {server_ip} -d egypt -U cleopatra
Where {server_ip}
is your server IP address, you will get a prompt to type your user
password, if the credentials match you’ll be logged into the Postgres
shell for cleopatra
and database egypt
.
Note: If you still cannot connect, you can reset your postgres user's password NOT linux default user
sudo -u postgres psql postgres
# \password postgres
Enter new password
Then use this new password to connect your pgAdmin4 using
postgres as Maintenance database
postgres as username
then new password
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”.
2. Next, navigate to the django-projects directory.
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.
root@dbserver:~# apt-get install python3-venv
khalil@dbserver:~$
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:
2. Verify that Django was installed by typing python in your shell. At the interactive Python prompt, try to import Django:
>>> print(django.get_version())
4.0
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.Running this command creates a default folder structure, which includes some Python files and your management app that has the same name as your project:
djangoPostgres/
│
├──
djangoPostgres/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
│
└── manage.py
- 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.
Step 7 — Start a Django App
1. Inside your project folder (../django-projects/djangoPostgres/ ), run the following command to start your first app:>>> import shutil
>>> shutil.rmtree('django-projects/djangoPostgres/users')
2. Next, run the server to check that everything is okay:
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
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:
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.
'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:
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:
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
'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.
5. The final step is running the migrate command which will send your table to the 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.
No comments:
Post a Comment