Django RestApis CRUD Application with Angular 6 & PostgreSQL tutorial

django-angular-6-rest-api-postgresql-tutorial-feature-image

In this tutorial, we show you Angular 6 Http Client & Django Server example that uses Django to do CRUD with PostgreSQL (including finder method) and Angular 6 as front-end technology to make request and receive response.

Related Post: Django RestApis example – GET/POST/PUT/DELETE requests to PostgreSQL database

Technologies

– Django 2.1
– Angular 6
– RxJS 6
– PostgreSQL 9.5

Project Overview

1. Django Server

django-angular-6-rest-api-postgresql-django-server-architecture

With this system, we can use Angular Client to work with PostgreSQL Database via Django Server which has APIs:

  • GET api/customers/: get all customers
  • GET api/customers/[id]: get a customer by id
  • GET api/customers/age/[age]: find all customers by age
  • POST api/customers/: save a customer
  • PUT api/customers/[id]: update a customer by id
  • DELETE api/customers/[id]: delete a customer by id
  • DELETE api/customers/: delete all customers

2. Angular 6 Client

The image below shows overview about Angular Components that we will create:

django-angular-6-rest-api-postgresql-django-angular-client-component

Django RestApi server

Project structure

There are several folders and files in our Django project:

django-angular-6-rest-api-postgresql-django-project-structure

customers/apps.py: declares CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration.
gkzRestApi/settings.py: configures settings for the Django project, including INSTALLED_APPS list with Django REST framework and Customers Application.
customers/models.py: defines Customer data model class (subclass of the django.db.models.Model).
migrations/0001_initial.py: is generated by makemigrations command, includes the code to create the Customer model, will be run by migrate to generate PostgreSQL database table for Customer model.
customers/serializers.py: declares CustomerSerializer class (subclass of rest_framework.serializers.ModelSerializer) for Customer instances to manage serialization to JSON and deserialization from JSON.
customers/views.py: contains methods to process HTTP requests and produce HTTP responses (using CustomerSerializer).
customers/urls.py: defines urlpatterns to be matched with request functions in the views.py.
gkzRestApi/urls.py: defines root URL configurations that includes the URL patterns declared in customers/urls.py.

Setup Django RestApi project

Install Django REST framework

Django REST framework works on top of Django and helps us to build RESTful Web Services flexibly. To install this package, run command:
pip install djangorestframework

Create RestApi project

Create Django project named gkzRestApi with command:
django-admin startproject gkzRestApi

django-angular-6-rest-api-postgresql-django-create-project

Install Python PostgreSQL adapter

We have to install Python PostgreSQL adapter to work with PostgreSQL database.
In this tutorial, we use psycopg2: pip install psycopg2.

Setup PostgreSQL Database engine

Open gkzRestApi/settings.py and change declaration of DATABASES:

Create Customers App

Run following commands to create new Django App named customers:
cd gkzRestApi
python manage.py startapp customers

django-angular-6-rest-api-postgresql-django-create-project-app

Open customers/apps.py, we can see CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration:

Add Django Rest framework & RestApi App to Django project

Open gkzRestApi/settings.py, find INSTALLED_APPS, then add:

Add CORS Configurations

Inside gkzRestApi/settings.py, add:

Implement Django RestApi App

Data Model
Create Data Model

customers/models.py

Run initial migration for data model

Run following Python script:
python manage.py makemigrations customers

We can see output text:

It indicates that the customers/migrations/0001_initial.py file includes code to create Customer data model:

The generated code defines a subclass of the django.db.migrations.Migration. It has an operation for creating Customer model table. Call to migrations.CreateModel() method will create a table that allows the underlying database to persist the model.

Run the following Python script to apply the generated migration:
python manage.py migrate customers

The output text:

Check PostgreSQL Database, now we can see that a table for Customer model was generated and it’s named customers_customer:

django-angular-6-rest-api-postgresql-django-postgresql-table

Create Serializer class

We need a Serializer class for Customer instances to manage serialization to JSON and deserialization from JSON.

– This CustomerSerializer will inherit from rest_framework.serializers.ModelSerializer superclass.
ModelSerializer class automatically populates a set of default fields and default validators, we only need to specify the model class.

Now, under customers package, create serializers.py file:

Meta inner class declares 2 attributes:
model: specifies the model related to the serializer
fields: specifies a tuple of field names that we want to include in the serialization

Create API Views

Open customers/views.py file and declare two functions:
customer_list(): get list of customers, save a new customer, delete all customers
customer_detail(): get/update/delete customer by ‘id’
customer_list_age(): find all customers by ‘age’

Route Urls to Views functions

Create urls.py in customers folder, now we will define urlpatterns to be matched with request functions in the views.py.

Now we must include above URL patterns in root URL configurations.
Open gkzRestApi/urls.py, replace the code:

Angular Client

Project Structure

django-angular-6-rest-api-postgresql-angular-project-structure

We have:
– 4 components: customers-list, customer-details, create-customer, search-customer.
– 3 modules: FormsModule, HttpClientModule, AppRoutingModule.
customer.ts: class Customer (id, firstName, lastName)
customer.service.ts: Service for Http Client methods
app-routing.module.ts: Routing configuration

Setup Angular Project

Create Angular Project

Run command: ng new AngularDjango.

Create Service & Components

On Project folder, run commands below:
ng g s customer
ng g c create-customer
ng g c customer-details
ng g c customers-list
ng g c search-customers

On each Component selector, delete app- prefix, then change tslint.json rules"component-selector" to false.

App Module

Check app.module.ts file, we can see Angular Components & Service are added automatically.
Now we need to import FormsModule, HttpClientModule for using form submission and HTTP requests to Django server. We also import AppRoutingModule for routing (will be created later in this tutorial).

Implement Angular Client App

Data Model

Create new file named customer.ts:

Data Service

This service uses Angular HttpClient object to make get/post/put/delete request to Django Rest Api Server.

customer.service.ts

Components
List of Customers

This component calls Data service’s getCustomersList() function, then shows the result as Customer list. It also has deleteCustomers() function that calls Data service’s deleteAll() function to delete all customers.

customers-list/customers-list.component.ts

customers-list/customers-list.component.html

This template embeds customer-details component that we will implement right here.

Customer Details

customer-details/customer-details.component.ts

As you can see, this component receives input Customer data object from parent component (CustomersListComponent), then apply the information on Data service’s functions: updateCustomer() and deleteCustomer()..

customer-details/customer-details.component.html

Create Customer

This component uses Data service’s createCustomer() function to save Customer information to the database.

create-customer/create-customer.component.ts

create-customer/create-customer.component.html

Search Customers

This component uses Data services’s getCustomersByAge() function as finder method to find customers by age

search-customers/search-customers.component.ts

search-customers/search-customers.component.html

Add Router

app-routing.module.ts

And AppComponent HTML for routing:

app.component.html

Run & Check Results

– Run Django server with command: python manage.py runserver.
– Run Angular App with command: ng serve.
– Open browser for url http://localhost:4200/:

Add Customer:

django-rest-api-crud-app-angular-example-postgresql-create-customer

Check database after saving Customers:

django-rest-api-crud-app-angular-example-postgresql-show-customers-database

Show Customers:

django-rest-api-crud-app-angular-example-postgresql-show-customers

Click on Active button to update Customer status:

django-rest-api-crud-app-angular-example-postgresql-update-customers

Check database after updating:

django-rest-api-crud-app-angular-example-postgresql-update-customers-database

Search Customers by Age:

django-rest-api-crud-app-angular-example-postgresql-search-customers

Delete a Customer:

django-rest-api-crud-app-angular-example-postgresql-delete-a-customer

Check database after deleting a Customer:

django-rest-api-crud-app-angular-example-postgresql-delete-a-customer-database

Delete All Customers:

django-rest-api-crud-app-angular-example-postgresql-delete-all-customers

Now the table is empty:

django-rest-api-crud-app-angular-example-postgresql-delete-all-customers-database

Source Code

Django-RestApi-server-PostgreSQL
AngularDjango-PostgreSQL

By grokonez | March 7, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*