This tutorial will teach you how to do the full stack development application using Django with Angular that are CREATE, RETIEVE, UPDATE and DELETE and SEARCH using mysql Database. The INSERT, SELECT, UPDATE and DELETE statements can be used in any database system, because this is support by all relational database systems.Django is world best Python Framework for developing the webapplications.
Let Learn How to Make the System Step by Step
Install the Django
1 | pip install django==3.2 |
After install Django lets create the django Project
Create Django Project
1 | django-admin startproject SchoolProject . |
Lets Run the Project Using Following Command
1 | python manage.py runserver |
Now you can see the welcome page of django.
After that lets configure the database mysql.
Lets Install Mysql
1 | pip install pymysql |
After that lets Upgrade the Version
1 | pip install pymysql --upgrade |
After that go to mysql database i used in this example xampp server. and create the database kms.
Lets Create the Virtual Environment type the following command
1 | python -m venv Env |
after run the command there is a folder created which name is Env.inside the Env folder there is file which is created Scripts. lets go inside the folder type the following command
1 | cd Env\Scripts |
then need to activated so type the following command
1 | activate |
Now you can see the Virtual Environment is activated successfully. then type the following command. come to backward
1 | cd ../.. |
now you in the Virtual Environment lets install the Django again
1 | pip install django==3.2 |
After that will create the App which name is StudentApp
1 | python manage.py startapp StudentApp |
StudentApp we have to added in to the setting.py
1 | 'StudentApp.apps.StudentappConfig' |
After that Create the Model
models.py
1 2 3 4 5 6 | from django.db import models class Student(models.Model): name = models.CharField(max_length = 255) address = models.CharField(max_length = 255) fee = models.IntegerField() |
Install the CORS
1 | pip install django-cors-headers |
Install the Rest Framework
1 | pip install djangorestframework |
Add the dependencies in to the settings.py inside the INSTALLED_APPS
1 2 3 | 'corsheaders', 'rest_framework', 'StudentApp.apps.StudentappConfig' |
1 | 'corsheaders.middleware.CorsMiddleware', |
in to the settings.py you have add CORS_ORIGIN Setting make both as true
1 2 | CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_ALL_HEADERS=True |
Angular Connected Port
1 2 3 | CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] |
After that select StudentApp Folder inside the create the file serializers.py
serializers.py
1 2 3 4 5 6 7 | from rest_framework import serializers from StudentApp.models import Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' |
After that lets Configure the Mysql Database into our Django Project
Install the database Url type by the following command
1 | pip install dj-database-url |
After that Install the mysqlclient
1 | pip install mysqlclient |
After that Configure the database connection on settings.py
settings.py
1 2 3 | import dj_database_url DATABASES['default'] = dj_database_url.parse('mysql://root@localhost/kms') |
After that run the migration command
1 | python manage.py makemigrations |
After done successfully. then type following command
1 | python manage.py migrate |
then you can see you database table has been created.
After that open views.py for generating views
views.py paste the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from StudentApp.serializers import StudentSerializer from StudentApp.models import Student @csrf_exempt def studentApi(request,id=0): if request.method=='GET': student = Student.objects.all() student_serializer=StudentSerializer(student,many=True) return JsonResponse(student_serializer.data,safe=False) elif request.method=='POST': student_data=JSONParser().parse(request) student_serializer=StudentSerializer(data=student_data) if student_serializer.is_valid(): student_serializer.save() return JsonResponse("Added Successfully",safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method=='PUT': student_data=JSONParser().parse(request) student=Student.objects.get(id=id) student_serializer=StudentSerializer(student,data=student_data) if student_serializer.is_valid(): student_serializer.save() return JsonResponse("Updated Successfully",safe=False) return JsonResponse("Failed to Update") elif request.method=='DELETE': student=Student.objects.get(id=id) student.delete() return JsonResponse("Deleted Successfully",safe=False) |
Manage the Urls
Urls.py paste the code
1 2 3 4 5 6 7 8 9 10 11 | from django.contrib import admin from django.urls import path from django.conf.urls import url from StudentApp import views urlpatterns = [ url(r'^student$',views.studentApi), url(r'^student$',views.studentApi), url(r'^student/([0-9]+)$',views.studentApi), path('admin/', admin.site.urls), ] |
Run the Project
1 | python manage.py runserver |
Angular
Angular is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.
Installing Angular CLI
1 | npm install -g @angular/cli |
After that create the new Project of Angular running by the following command
1 | ng new frond-end |
After complete the installation then run the project using following command.
1 | ng serve |
Now you see the Angular Welcome Page.
After that open the Angular project into VS code editor.
now you can see the following file structure
Creating a new Component Student Crud
1 | ng g c crud |
1 2 3 4 5 6 7 8 | <head> <meta charset="utf-8"> <title>MyFirstProject</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> </head> |
app.module.ts
add these following modules inside the app.module.ts. FormModule,HttpClientModule
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CrudComponent } from './crud/crud.component'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, CrudComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
crud.compoent.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <div class="container mt-4" > <h1>STUDENT Registation</h1> <div class="card"> <form> <div class="form-group"> <label >Student Name</label> <input type="text" [(ngModel)]="name" [ngModelOptions]="{standalone: true}" class="form-control" id="studentname" name="studentname" placeholder="Enter Name"> </div> <div class="form-group"> <label >Address</label> <input type="text" [(ngModel)]="address" [ngModelOptions]="{standalone: true}" class="form-control" id="studentaddress" name="studentaddress" placeholder="Enter Address"> </div> <div class="form-group"> <label >Mobile</label> <input type="text" [(ngModel)]="fee" [ngModelOptions]="{standalone: true}" class="form-control" id="fee" name="text" placeholder="Enter Fee"> </div> <button type="submit" class="btn btn-primary mt-4" (click)="saveRecords()" >Save</button> <button type="submit" class="btn btn-warning mt-4" (click)="UpdateRecords()" >Update</button> </form> </div> </div> <div> <div class="container mt-4" > <h1>Student Table</h1> <table class="table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Fee</th> <th scope="col">Option</th> </tr> </thead> <tbody> <tr *ngFor="let StudentItem of StudentArray"> <td>{{StudentItem.name}}</td> <td>{{StudentItem.address }}</td> <td>{{StudentItem.fee }}</td> <td> <button type="button" class="btn btn-success" (click)="setUpdate(StudentItem)">Edit</button> <button type="button" class="btn btn-danger" (click)="setDelete(StudentItem)">Delete</button> </td> </tr> </tbody> </table> </div> |
crud.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Component({ selector: 'app-crud', templateUrl: './crud.component.html', styleUrls: ['./crud.component.scss'] }) export class CrudComponent { StudentArray : any[] = []; name: string =""; address: string =""; fee: Number =0; currentStudentID = ""; constructor(private http: HttpClient ) { this.getAllStudent(); } saveRecords() { let bodyData = { "name" : this.name, "address" : this.address, "fee" : this.fee }; this.http.post("http://127.0.0.1:8000/student",bodyData).subscribe((resultData: any)=> { console.log(resultData); alert("Student Registered Successfully"); this.getAllStudent(); }); } getAllStudent() { this.http.get("http://127.0.0.1:8000/student") .subscribe((resultData: any)=> { console.log(resultData); this.StudentArray = resultData; }); } setUpdate(data: any) { this.name = data.name; this.address = data.address; this.fee = data.fee; this.currentStudentID = data.id; } UpdateRecords() { let bodyData = { "name" : this.name, "address" : this.address, "fee" : this.fee }; this.http.put("http://127.0.0.1:8000/student/"+ this.currentStudentID , bodyData).subscribe((resultData: any)=> { console.log(resultData); alert("Student Registered Updateddd") this.name = ''; this.address = ''; this.fee = 0; this.getAllStudent(); }); } setDelete(data: any) { this.http.delete("http://127.0.0.1:8000/student"+ "/"+ data.id).subscribe((resultData: any)=> { console.log(resultData); alert("Student Deletedddd") this.getAllStudent(); }); } } |