DEV Community

Harlin Seritt
Harlin Seritt

Posted on

Angular + Django Rest Framework - A Winning Combo!

Angular and Django Rest Framework (DRF) are two popular frameworks that can be used together to create powerful and scalable web applications.

  1. Angular is a powerful front-end framework for building dynamic, single-page web applications

  2. DRF is a robust back-end framework for building RESTful APIs in Django.

Together, they provide a complete solution for building full-stack web applications.

Separation of Concerns

One of the major advantages of using Angular with DRF is the separation of concerns:

Angular handles the front-end logic and user interface, while DRF handles the back-end logic and data storage.

This separation allows for a clean and maintainable codebase, as well as the ability to easily switch out one piece of the stack without affecting the other.

Setup Summary

To get started, you will first need to set up a Django project and install DRF (See https://dev.to/hseritt/django-rest-framework-2e0k for more details).

Once that is done, you can start building your RESTful API using views, serializers, and routers provided by DRF.

This will allow you to access your data from the Angular application.

On the Angular side, you can use the HttpClient module to make HTTP requests to your DRF endpoints.

This can be used to retrieve data from the back-end and display it on the front-end, as well as to send data to the back-end to be stored.

Angular also provides a powerful data binding feature that allows you to easily keep your front-end and back-end in sync.

This allows you to create dynamic and responsive user interfaces that update in real-time based on changes in the data.

DRF provides built-in support for authentication and permissions, while Angular provides powerful tools for handling user authentication and authorization on the front-end.

Finally, Angular and DRF are both highly modular and extensible frameworks. This allows you to easily add new features and functionality to your application as your needs change.

Setup DRF

Here is an example of how to set up a Task model with Django Rest Framework (DRF):

Create a new app in your Django project by running the command python manage.py startapp tasks.

In the models.py file of the new tasks app, define the Task model with fields such as title, description and created_at:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
Enter fullscreen mode Exit fullscreen mode

In the views.py file of the tasks app, import the Task model and create a serializer class for it:

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('id', 'title', 'description', 'created_at')
Enter fullscreen mode Exit fullscreen mode

In the views.py file, create views for the Task model using the DRF's generic views such as ListAPIView, RetrieveAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView:

from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
Enter fullscreen mode Exit fullscreen mode

In the urls.py file of the tasks app, import the TaskViewSet and add it to the router:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
Enter fullscreen mode Exit fullscreen mode

Finally, include the tasks app's urls in the project's urls.py file:

from django.urls import path, include

urlpatterns = [
    path('api/', include('tasks.urls')),
]
Enter fullscreen mode Exit fullscreen mode

With this setup, you will have a working Task model that you can interact with through the RESTful API provided by DRF. You can create, read, update and delete tasks using the appropriate endpoints, and the serializer will ensure that the data is properly validated and formatted. We'll go through each of these in the following sections.

Front-End (Angular)

Read

Here is an example of how to set up an Angular component that uses the Task model from Django Rest Framework (DRF):

In your Angular project, create a new component called task-list by running the command ng generate component task-list.

In the task-list.component.ts file, import the necessary modules such as HttpClient and Observable:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Task } from './task';
Enter fullscreen mode Exit fullscreen mode

In the same file, define the Task interface and create a property to hold the tasks:

export interface Task {
    id: number;
    title: string;
    description: string;
    created_at: string;
}

@Component({
  selector: 'app-task-list',
  templateUrl: './task-list.component.html',
  styleUrls: ['./task-list.component.css']
})

export class TaskListComponent implements OnInit {
  tasks: Task[];
  ...
Enter fullscreen mode Exit fullscreen mode

In the constructor(), inject the HttpClient and define the API endpoint for the tasks:

constructor(private http: HttpClient) { }
private apiUrl = 'http://localhost:8000/api/tasks/';
Enter fullscreen mode Exit fullscreen mode

In the ngOnInit() lifecycle method, use the http.get() method to retrieve the tasks from the API and assign them to the tasks property:

ngOnInit() {
    this.getTasks().subscribe((tasks: Task[]) => {
        this.tasks = tasks;
    });
}

getTasks(): Observable<Task[]> {
    return this.http.get<Task[]>(this.apiUrl);
}
Enter fullscreen mode Exit fullscreen mode

In the task-list.component.html file, use *ngFor directive to display the tasks:

<table>
    <tr *ngFor="let task of tasks">
        <td>{{ task.title }}</td>
        <td>{{ task.description }}</td>
        <td>{{ task.created_at }}</td>
    </tr>
</table>
Enter fullscreen mode Exit fullscreen mode

With this setup, you will have a working Angular component that displays a list of tasks fetched from the Django Rest Framework API. You can also use other methods provided by the HttpClient module such as http.post(), http.put() and http.delete() to create, update and delete tasks from the API.

Create

Here's an example of how to use the http.post() method with the task-list component to create a new task:

In the task-list.component.ts file, import the FormsModule and add it to the imports array in the @NgModule decorator.

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    // Other imports
  ],
  // ...
Enter fullscreen mode Exit fullscreen mode

Add a new property to hold the data for the new task and create a function to handle the form submission:

newTask: Task = { title: '', description: '' };

createTask() {
    this.http.post(this.apiUrl, this.newTask)
    .subscribe(() => {
        // code to refresh the task list goes here
    });
}
Enter fullscreen mode Exit fullscreen mode

In the task-list.component.html file, add a form to create a new task and bind it to the newTask property using ngModel. Also, add a button to submit the form and call the createTask() function:

<form (ngSubmit)="createTask()">
    <input type="text" [(ngModel)]="newTask.title" name="title" placeholder="Title">
    <input type="text" [(ngModel)]="newTask.description" name="description" placeholder="Description">
    <button type="submit">Create Task</button>
</form>
Enter fullscreen mode Exit fullscreen mode

With this setup, you will have a working form that allows you to create a new task by sending a POST request to the Django Rest Framework API.
You can also add some validations and error handling in your code.

Note that in the subscribe function, you can refresh the task list by calling the getTasks() method again and updating the tasks property with the new data.

Update

Here's an example of how to use the http.put() method with the task-list component to update an existing task:

In the task-list.component.ts file, add a new function to handle the task update:

updateTask(task: Task) {
    this.http.put(`${this.apiUrl}/${task.id}`, task)
    .subscribe(() => {
        // code to refresh the task list goes here
    });
}
Enter fullscreen mode Exit fullscreen mode

In the task-list.component.html file, add a button next to each task that calls the updateTask() function when clicked:

<ul>
    <li *ngFor="let task of tasks">
        {{ task.title }} - {{ task.description }}
        <button (click)="updateTask(task)">Update Task</button>
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

With this setup, you will have a working button that allows you to update an existing task by sending a PUT request to the Django Rest Framework API.

It's important to note that the put method needs the specific ID of the task to be updated, and in this example we're passing the task object to the updateTask function.

Note that in the subscribe function, you can refresh the task list by calling the getTasks() method again and updating the tasks property with the new data.

Delete

Here's an example of how to use the http.delete() method with the task-list component to delete an existing task:

In the task-list.component.ts file, add a new function to handle the task deletion:

deleteTask(task: Task) {
    this.http.delete(`${this.apiUrl}/${task.id}`)
    .subscribe(() => {
        // code to refresh the task list goes here
    });
}
Enter fullscreen mode Exit fullscreen mode

In the task-list.component.html file, add a button next to each task that calls the deleteTask() function when clicked:

<ul>
    <li *ngFor="let task of tasks">
        {{ task.title }} - {{ task.description }}
        <button (click)="deleteTask(task)">Delete Task</button>
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

With this setup, you will have a working button that allows you to delete an existing task by sending a DELETE request to the Django Rest Framework API.

Note that the delete method needs the specific ID of the task to be deleted, and in this example we're passing the task object to the deleteTask function.

Note that in the subscribe function, you can refresh the task list by calling the getTasks() method again and updating the tasks property with the new data.

Also, it's important to note that the delete method is a destructive operation, so you may want to add a confirmation dialog to the delete button so that the user is aware of what they're doing.

Summary

Angular and Django Rest Framework provide a powerful and flexible solution for building full-stack web applications.

They allow you to easily separate concerns, creating a clean and maintainable codebase.

They also provide powerful tools for creating dynamic and responsive user interfaces, as well as built-in support for authentication and authorization.

Together, they provide a complete solution for building scalable and robust web applications.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!