Django + Angular 11 Tutorial: CRUD App Django Rest Framework
Django + Angular 11 Tutorial: CRUD App Django Rest Framework
In this tutorial, we will learn how to build a full stack Django + Angular 11 example
with a CRUD App. The back-end server uses Python 3/Django with Rest Framework
for REST APIs. Front-end side is made with Angular 11, HTTPClient & Router.
Other versions:
– using Angular 8
– using Angular 10
– using Angular 12
– using Angular 13
Contents [hide]
Django Angular 11 example Overview
Architecture of Django Angular 11 Tutorial Application
Django Rest Apis Back-end
o Overview
o Technology
o Project Structure
o Implementation
Install Django REST framework
Setup new Django project
Setup Database engine
Setup new Django app for Rest CRUD Api
Configure CORS
Define the Django Model
Migrate Data Model to the database
Create Serializer class for Data Model
Define Routes to Views functions
Write API Views
Run the Django Rest Api Server
Angular 11 Front-end
o Overview
o Project Structure
o Implementation
Setup Angular 11 Project
Set up App Module
Define Routes for Angular AppRoutingModule
Create Data Service
Create Angular Components
Run the Angular 11 App
Further Reading
Conclusion
– Django exports REST Apis using Django Rest Framework & interacts with Database
using Django Model.
– Angular Client sends HTTP Requests and retrieve HTTP Responses using HttpClient
Module, shows data on the components. We also use Angular Router for navigating
to pages.
Overview
These are APIs that Django App will export:
Project Structure
This is our Django project structure:
class TutorialsConfig(AppConfig):
name = 'tutorials'
Don’t forget to add this app to INSTALLED_APPS array in settings.py:
INSTALLED_APPS = [
...
# Tutorials application
'tutorials.apps.TutorialsConfig',
]
Configure CORS
We need to allow requests to our Django application from other origins.
In this example, we’re gonna configure CORS to accept requests
from localhost:8081.
First, install the django-cors-headers library:
pip install django-cors-headers
In settings.py, add configuration for CORS:
INSTALLED_APPS = [
...
# CORS
'corsheaders',
]
You also need to add a middleware class to listen in on responses:
MIDDLEWARE = [
...
# CORS
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
Note: CorsMiddleware should be placed as high as possible, especially before any
middleware that can generate responses such as CommonMiddleware.
Next, set CORS_ORIGIN_ALLOW_ALL and add the host to CORS_ORIGIN_WHITELIST:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8081',
)
class Tutorial(models.Model):
title = models.CharField(max_length=70, blank=False, default='')
description = models.CharField(max_length=200,blank=False,
default='')
published = models.BooleanField(default=False)
Each field is specified as a class attribute, and each attribute maps to a database
column.
id field is added automatically.
Migrate Data Model to the database
Run the Python script: python manage.py makemigrations tutorials.
The console will show:
Migrations for 'tutorials':
tutorials\migrations\0001_initial.py
- Create model Tutorial
Refresh the workspace, you can see new file tutorials/migrations/0001_initial.py.
It includes code to create Tutorial data model:
# Generated by Django 2.1.15
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Tutorial',
fields=[
('id', models.AutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='', max_length=70)),
('description', models.CharField(default='',
max_length=200)),
('published', models.BooleanField(default=False)),
],
),
]
The generated code defines Migration class (subclass of
the django.db.migrations.Migration).
It has operations array that contains operation for creating Tutorial model
table: migrations.CreateModel().
The call to this will create a new model in the project history and a corresponding
table in the database to match it.
To apply the generated migration above, run the following Python script:
python manage.py migrate tutorials
The console will show:
Operations to perform:
Apply all migrations: tutorials
Running migrations:
Applying tutorials.0001_initial... OK
At this time, you can see that a table/collection for Tutorial model was generated
automatically with the name: tutorials_tutorial in the database.
Create Serializer class for Data Model
Let’s create TutorialSerializer class that will manage serialization and
deserialization from JSON.
It inherit from rest_framework.serializers.ModelSerializer superclass
which automatically populates a set of fields and default validators. We need to
specify the model class here.
tutorials/serializers.py
from rest_framework import serializers
from tutorials.models import Tutorial
class TutorialSerializer(serializers.ModelSerializer):
class Meta:
model = Tutorial
fields = ('id',
'title',
'description',
'published')
In the inner class Meta, we declare 2 attributes:
urlpatterns = [
url(r'^api/tutorials$', views.tutorial_list),
url(r'^api/tutorials/(?P<pk>[0-9]+)$', views.tutorial_detail),
url(r'^api/tutorials/published$', views.tutorial_list_published)
]
Don’t forget to include this URL patterns in root URL configurations.
Open bzkRestApis/urls.py and modify the content with the following code:
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('tutorials.urls')),
]
Write API Views
We’re gonna create these API functions for CRUD Operations:
– tutorial_list(): GET list of tutorials, POST a new tutorial, DELETE all tutorials
– tutorial_detail(): GET / PUT / DELETE tutorial by ‘id’
– tutorial_list_published(): GET all published tutorials
Open tutorials/views.py and write following code:
from django.shortcuts import render
...
@api_view(['GET'])
def tutorial_list_published(request):
# GET all published tutorials
You can continue with step by step to implement this Django Server in one of the
posts:
Angular 11 Front-end
Overview
– The App component is a container with router-outlet. It has navbar that links to
routes paths via routerLink.
– TutorialsList component gets and displays Tutorials.
– TutorialDetails component has form for editing Tutorial’s details based
on :id.
– AddTutorial component has form for submission new Tutorial.
– These Components call TutorialService methods which use
Angular HTTPClient to make HTTP requests and receive responses.
Project Structure
ng g c components/add-tutorial
ng g c components/tutorial-details
ng g c components/tutorials-list
@NgModule({
declarations: [ ... ],
imports: [
...
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Define Routes for Angular AppRoutingModule
There are 3 main routes:
– /tutorials for tutorials-list component
– /tutorials/:id for tutorial-details component
– /add for add-tutorial component
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TutorialsListComponent } from
'./components/tutorials-list/tutorials-list.component';
import { TutorialDetailsComponent } from './components/tutorial-
details/tutorial-details.component';
import { AddTutorialComponent } from './components/add-tutorial/add-
tutorial.component';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Create Data Service
This service will use Angular HTTPClient to send HTTP requests.
You can see that its functions includes CRUD operations and finder method.
services/tutorial.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tutorial } from '../models/tutorial.model';
@Injectable({
providedIn: 'root'
})
export class TutorialService {
deleteAll(): Observable<any> {
return this.http.delete(baseUrl);
}
You can continue with step by step to implement this Angular 11 App in the post:
Angular 11 CRUD Application example with Web API
Other versions:
– Angular 8 CRUD example with Web API
– Angular 10 CRUD example with Web API
– Angular 12 CRUD example with Web API
– Angular 13 CRUD example with Web API
– Angular 14 CRUD example with Web API
– Angular 15 CRUD example with Web API
Run the Angular 11 App
You can run this App with command: ng serve --port 8081.
If the process is successful, open Browser with Url: http://localhost:8081/ and
check it.
Further Reading
Conclusion
Now we have an overview of Angular 11 Django example when building a CRUD App that
interacts with database. We also take a look at client-server architecture for REST API
using Django Rest Framework (Python 3), as well as Angular 11 project structure for
building a front-end