How to use PostgreSQL database in Django

Overview

Django is an open-source, high-level Python web framework that encourages rapid development, and clean, pragmatic design.

In this shot, we will be looking into PostgreSQL with Django.

PostgreSQL is an object-relational database that uses and extends the SQL language to scale and store big, complicated data in the database.

The example below demonstrates how PostgreSQL can be used alongside Django.

How to install

Step 1

pip install pipenv
pipenv shell
pipenv install django

Then:

Step 2

django-admin startproject DjangoPostgreSql ./

python manage.py startapp codebase

Step 3

python manage.py migrate
python manage.py runserver

Step 4

The “settings.py” file

settings.py” helps register the application and packages that are being installed, and even writes rules.

Once the settings have been initialized, the following changes should be made.

Here, we will see how to initialize a PostgreSQL database to a Django app.

Go to “settings.py” and enter the following:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'codebase'
]
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# adding the postgresql settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'real_estate', # name of the database
'USER': 'postgres', # username of the databasee
'PASSWORD': '12345', #password of your postgresql app
'HOST': 'localhost' # name of the host
}
}

Step 5

The code below is added to the “models.py” file in the codebase app folder.

The “models.py” file

This file is responsible for creating the model for the database.

from django.db import models
from django.urls import reverse
class CRUD(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
level = models.CharField(max_length=30)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name

Step 6

The “admin.py” file

In this file, we will import and register our created model. By doing so, we can view the model when we are logged in as an administrator.

from django.contrib import admin
from .models import CRUD
admin.site.register(CRUD)

Step 7

The “forms.py” file

With the configuration complete, you can create a file for the form. In our case, the file is named “forms.py”.

The forms file is responsible for creating Django forms, which are like HTML forms, but dynamic.

from django import forms
from .models import CRUD
class CRUDFORM(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "name"
}))
age= forms.CharField(widget=forms.TextInput(attrs={
'type': "number",
"class": "form-control",
"placeholder": "age"
}))
level = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "level"
}))
class Meta:
model = CRUD
fields = [
'name', 'age','level'
]

Step 8

The “views.py” file

You can now create a view for your project with the form created. The corresponding “views.py” file is shown below:

This file is used to create functions or classes that visualize how a route will operate.

from django.shortcuts import redirect, render, get_object_or_404
from .models import CRUD
from .forms import CRUDFORM
def home(request):
queryset = CRUD.objects.all().order_by('-date')
context = {
'queryset': queryset
}
return render(request, 'app/base.html', context)
def create(request):
form = CRUDFORM(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect ('home')
context = {
"form":form
}
return render(request, 'app/createform.html', context)

Step 9

The “base.html” file

  • In the codebase app, create a folder and name it templates.
  • Inside the “templates” folder, create another folder and name it “app”.
  • Inside the “app” folder, create “base.html” and 'createform.html' files.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<div class="container mt-3">
<!-- this code block is used to used to create a url link -->
<a href="{% url 'create'%}" >link to create a form</a>
<hr>
<!-- this code bloack is used to loop the data in the database -->
{% for data in queryset %}
<div class="list-group mb-3">
<a href="#" class="list-group-item list-group-item-action">Name: {{data.name}}</a>
<a href="#" class="list-group-item list-group-item-action">Age: {{data.age}}</a>
<a href="#" class="list-group-item list-group-item-action">Level: {{data.level}}</a>
</div>
{% endfor %}
<hr>
</div>
</body>
</html>

Step 10

The “createform.html” file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<form method="POST" action="">
<!-- for csrf token -->
{% csrf_token %}
<div class="form-group mb-3">
<!-- double curly braces is used to display data from the database -->
{{form.name}}
{{form.name}}
{{form.name.errors}}
</div>
<div class="form-group mb-3">
{{form.age}}
{{form.age.errors}}
</div>
<div class="form-group mb-3">
{{form.level}}
{{form.level.errors}}
</div>
<input type="submit" class="btn btn-outline-success" >
</form>
</div>
</body>

Step 11

The “urls.py” file

The “urls.py” file is used to create a different url route.

Go to the DjangoPostgreSQL folder, and make the following amends in “urls.py”:

from django.contrib import admin
from django.urls import path, include
# importing from app folder, the view file
from app.view import home, create
urlpatterns = [
path('admin/', admin.site.urls),
# for the home function in the view file
path('', home, name="home"),
# for the create function in the view file
path('create/', create, name="create")
]

Step 12

Now that we’re ready, run the following commands to make migrations to the code:

python manage.py makemigrations

python manage.py migrate

Step 13

In case you want to create a super-user, run the following command:

python manage.py createsuperuser

After that, run:

Step 14

To start the server, run:

python manage.py runserver

If you want to access the admin panel, visit https://127.0.0.1:8000/admin on your local machine .

Or

https://127.0.0.1:8000 to access the homepage.

Free Resources