In this tutorial, you will learn how to create a full stack
web application from scratch using Mongo DB for the database, Python Django for
the backend, and Vue JS for the front end.
We will first start with installing and setting up the
environment for the project.
Then we create the Python Django project with the required
rest API end points using Django REST Framework.
Finally we will use Vue JS for creating the front end.
-You will learn how to add routing for our app.
-Create bootstrap table with custom sorting and filtering
capabilities.
-Add modal pop up window with drop downs and date pickers.
VIDEO
-We will also learn how to upload an image and store it in
the backend server.
Lets install the necessary modules needed for our Django project.
First lets install the Django module.
>> pip install django
To create rest APIs we need to install Django rest framework.
>> pip install djangorestframework
By default, the Django project comes with a security that blocks requests coming from different domains. To disable this, lets install Django CORS headers module.
>> pip install django-cors-headers
Now lets create the Django project.
Open the command prompt in the desired folder and type the command.
>> django-admin start project <name of the project>
Lets take a look at some of the important files in the project.
>> __init__.py file is just and empty file that indicates that the given folder is a python project or a python module.
>> asgi.py is the entry point for the asgi compatible webservers.
>> wsgi.py is the entry point for the wsgi compatible web servers.
>> urls.py file contains all the url declarations needed for this project.
>> settings.py file contains all the settings or the configurations needed for the project.
>> manage.py is a command line utility that helps interact with the Django project.
Lets simply run the project and see how it looks in the browser using below command.
>> python manage.py runserver
The app is now running in the port 8000.
Lets copy the url and open in the browser.
What you see on the screen is the default template that comes with every Django project.
Now lets create an app in our Django project.
Quick difference between projects and apps.
The folder structure that you currently see on the screen is called the project.
A project may have multiple apps.
For example, you can have one app which acts like a blog, or may be another app which acts like a survey form.
Currently this project does not have any app.
Lets create one app to implement our api methods.
To create an app, we need to type this command.
>> python manage.py startapp <the name of the app>
Next let us register the app and the required modules in settings.py file.
In the installed apps section, lets add Rest framework, cors header, and the newly created app.
We need to add the cors headers in middle ware section as well.
We will also add instruction to enable all domains to access the APIs.
This is not recommended in production. Instead, just add only those domains that needs to be whitelisted.
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
'corsheaders' ,
'EmployeeApp.apps.EmployeeappConfig'
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware' ,
'django.middleware.security.SecurityMiddleware' ,
'django.contrib.sessions.middleware.SessionMiddleware' ,
'django.middleware.common.CommonMiddleware' ,
'django.middleware.csrf.CsrfViewMiddleware' ,
'django.contrib.auth.middleware.AuthenticationMiddleware' ,
'django.contrib.messages.middleware.MessageMiddleware' ,
'django.middleware.clickjacking.XFrameOptionsMiddleware' ,
]
Lets create the models needed for our app.
We need two models.
One to store department details and another one to store employee details.
The departments model will have two fields. One to store an autoincremented Department ID, and another one to store Department Name.
Employee model will have five fields.
Employee ID, Employee name, Department, Date of joining, and photo file name which stores the uploaded profile picture file name.
Models.py complete code:
from django.db import models
# Create your models here.
class Departments (models. Model):
DepartmentId = models. AutoField(primary_key= True )
DepartmentName = models. CharField(max_length= 500 )
class Employees (models. Model):
EmployeeId = models. AutoField(primary_key= True )
EmployeeName = models. CharField(max_length= 500 )
Department = models. CharField(max_length= 500 )
DateOfJoining = models. DateField()
PhotoFileName = models. CharField(max_length= 500 )
We will be using the MongoDB database.
To connect to MongoDB from our Python Django app, we need to install the database adapter.
>> pip install djongo
Also, if we are connecting MongoDB atlas cloud DB, we need to install another module.
>> pip install dnspython
Add the database details in settings.py file.
Lets write the command to make migrations file for our models.
>> python manage.py makemigrations <app name>
After executing this, we can see a migration file which tells us what changes to the database will be done.
Once it looks fine, we can execute the command to push these changes to the database.
>> python manage.py migrate <app name>
Lets create serializers for our models.
Serializers basically help to convert the complex types or model instances into native python data types that can then be easily rendered into json or xml or other content types.
They also help in deserialization which is nothing but converting the passed data back to complex types.
serializers.py complete code:
from rest_framework import serializers
from EmployeeApp.models import Departments,Employees
class DepartmentSerializer (serializers. ModelSerializer):
class Meta :
model= Departments
fields= ('DepartmentId' ,'DepartmentName' )
class EmployeeSerializer (serializers. ModelSerializer):
class Meta :
model= Employees
fields= ('EmployeeId' ,'EmployeeName' ,'Department' ,'DateOfJoining' ,'PhotoFileName' )
Lets now start writing the API methods.
views.py code.
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from EmployeeApp.models import Departments,Employees
from EmployeeApp.serializers import DepartmentSerializer,EmployeeSerializer
from django.core.files.storage import default_storage
# Create your views here.
@csrf_exempt
def departmentApi (request,id = 0 ):
if request. method== 'GET' :
departments = Departments. objects. all()
departments_serializer= DepartmentSerializer(departments,many= True )
return JsonResponse(departments_serializer. data,safe= False )
elif request. method== 'POST' :
department_data= JSONParser(). parse(request)
departments_serializer= DepartmentSerializer(data= department_data)
if departments_serializer. is_valid():
departments_serializer. save()
return JsonResponse("Added Successfully" ,safe= False )
return JsonResponse("Failed to Add" ,safe= False )
elif request. method== 'PUT' :
department_data= JSONParser(). parse(request)
department= Departments. objects. get(DepartmentId= department_data['DepartmentId' ])
departments_serializer= DepartmentSerializer(department,data= department_data)
if departments_serializer. is_valid():
departments_serializer. save()
return JsonResponse("Updated Successfully" ,safe= False )
return JsonResponse("Failed to Update" )
elif request. method== 'DELETE' :
department= Departments. objects. get(DepartmentId= id )
department. delete()
return JsonResponse("Deleted Successfully" ,safe= False )
@csrf_exempt
def employeeApi (request,id = 0 ):
if request. method== 'GET' :
employees = Employees. objects. all()
employees_serializer= EmployeeSerializer(employees,many= True )
return JsonResponse(employees_serializer. data,safe= False )
elif request. method== 'POST' :
employee_data= JSONParser(). parse(request)
employees_serializer= EmployeeSerializer(data= employee_data)
if employees_serializer. is_valid():
employees_serializer. save()
return JsonResponse("Added Successfully" ,safe= False )
return JsonResponse("Failed to Add" ,safe= False )
elif request. method== 'PUT' :
employee_data= JSONParser(). parse(request)
employee= Employees. objects. get(EmployeeId= employee_data['EmployeeId' ])
employees_serializer= EmployeeSerializer(employee,data= employee_data)
if employees_serializer. is_valid():
employees_serializer. save()
return JsonResponse("Updated Successfully" ,safe= False )
return JsonResponse("Failed to Update" )
elif request. method== 'DELETE' :
employee= Employees. objects. get(EmployeeId= id )
employee. delete()
return JsonResponse("Deleted Successfully" ,safe= False )
@csrf_exempt
def SaveFile (request):
file = request. FILES['file' ]
file_name= default_storage. save(file . name,file )
return JsonResponse(file_name,safe= False )
For Save File API, create a folder with name 'Photos':
settings.py complete code:
"""
Django settings for DjangoAPI project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
BASE_DIR= Path(__file__). resolve(strict= True ). parent. parent
MEDIA_URL= '/Photos/'
MEDIA_ROOT= os. path. join(BASE_DIR,"Photos" )
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__). resolve(). parent. parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q %r 7c8*)%-&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
'corsheaders' ,
'EmployeeApp.apps.EmployeeappConfig'
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware' ,
'django.middleware.security.SecurityMiddleware' ,
'django.contrib.sessions.middleware.SessionMiddleware' ,
'django.middleware.common.CommonMiddleware' ,
'django.middleware.csrf.CsrfViewMiddleware' ,
'django.contrib.auth.middleware.AuthenticationMiddleware' ,
'django.contrib.messages.middleware.MessageMiddleware' ,
'django.middleware.clickjacking.XFrameOptionsMiddleware' ,
]
ROOT_URLCONF = 'DjangoAPI.urls'
TEMPLATES = [
{
'BACKEND' : 'django.template.backends.django.DjangoTemplates' ,
'DIRS' : [],
'APP_DIRS' : True ,
'OPTIONS' : {
'context_processors' : [
'django.template.context_processors.debug' ,
'django.template.context_processors.request' ,
'django.contrib.auth.context_processors.auth' ,
'django.contrib.messages.context_processors.messages' ,
],
},
},
]
WSGI_APPLICATION = 'DjangoAPI.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'CLIENT': {
"host":"mongodb+srv://<username>:<password>@<server>/myFirstDatabase?retryWrites=true&w=majority"
,"name":"<db name>",
"authMechanism":"SCRAM-SHA-1" #For atlas cloud db
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME' : 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' ,
},
{
'NAME' : 'django.contrib.auth.password_validation.MinimumLengthValidator' ,
},
{
'NAME' : 'django.contrib.auth.password_validation.CommonPasswordValidator' ,
},
{
'NAME' : 'django.contrib.auth.password_validation.NumericPasswordValidator' ,
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
EmployeeApp's urls.py:
from django.conf.urls import url
from EmployeeApp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns= [
url(r'^department$' ,views. departmentApi),
url(r'^department/([0-9]+)$' ,views. departmentApi),
url(r'^employee$' ,views. employeeApi),
url(r'^employee/([0-9]+)$' ,views. employeeApi),
url(r'^employee/savefile' ,views. SaveFile)
]+ static(settings. MEDIA_URL,document_root= settings. MEDIA_ROOT)
Main urls.py:
"""DjangoAPI URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
urlpatterns = [
path('admin/' , admin. site. urls),
url(r'^' ,include('EmployeeApp.urls' ))
]
Folder Structure of our Vue JS app:
index.html:
<! DOCTYPE html>
< head>
< link href= "https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel= "stylesheet" integrity= "sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin= "anonymous" >
< /head>
< body>
< div id= "app" class = "container" >
< h3 class = "d-flex justify-content-center" >
Vue JS Front End
< /h3>
< h5 class = "d-flex justify-content-center" >
Employee Management Portal
< /h5>
< nav class = "navbar navbar-expand-sm bg-light navbar-dark" >
< ul class = "navbar-nav" >
< li class = "nav-item m-1" >
< router- link class = "btn btn-light btn-outline-primary"
to= "/home" > Home< /router-link>
< /li>
< li class = "nav-item m-1" >
< router- link class = "btn btn-light btn-outline-primary"
to= "/department" > Department< /router-link>
< /li>
< li class = "nav-item m-1" >
< router- link class = "btn btn-light btn-outline-primary"
to= "/employee" > Employee< /router-link>
< /li>
< /ul>
< /nav>
< router- view>< /router-view>
< /div>
< script src= "variables.js" >< /script>
< script src= "https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" >< /script>
< script src= "https://unpkg.com/vue/dist/vue.js" >< /script>
< script src= "https://unpkg.com/vue-router/dist/vue-router.js" >< /script>
< script src= "home.js" >< /script>
< script src= "department.js" >
< /script>
< script src= "employee.js" >< /script>
< script src= "app.js" >< /script>
< script src= "https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity= "sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin= "anonymous" >< /script>
< /body>
< /html>
app.js:
const routes= [
{path: '/home' ,component: home},
{path: '/employee' ,component: employee},
{path: '/department' ,component: department}
]
const router= new VueRouter({
routes
})
const app = new Vue({
router
}).$mount('#app' )
department.js:
const department= {template: `
< div>
< button type= "button"
class = "btn btn-primary m-2 fload-end"
data- bs- toggle= "modal"
data- bs- target= "#exampleModal"
@ click= "addClick()" >
Add Department
< /button>
< table class = "table table-striped" >
< thead>
< tr>
< th>
< div class = "d-flex flex-row" >
< input class = "form-control m-2"
v- model= "DepartmentIdFilter"
v- on: keyup= "FilterFn()"
placeholder= "Filter" >
< button type= "button" class = "btn btn-light"
@ click= "sortResult('DepartmentId',true)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-arrow-down-square-fill" viewBox= "0 0 16 16" >
< path d= "M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
< /svg>
< /button>
< button type= "button" class = "btn btn-light"
@ click= "sortResult('DepartmentId',false)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-arrow-up-square-fill" viewBox= "0 0 16 16" >
< path d= "M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
< /svg>
< /button>
< /div>
DepartmentId
< /th>
< th>
< div class = "d-flex flex-row" >
< input class = "form-control m-2"
v- model= "DepartmentNameFilter"
v- on: keyup= "FilterFn()"
placeholder= "Filter" >
< button type= "button" class = "btn btn-light"
@ click= "sortResult('DepartmentName',true)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-arrow-down-square-fill" viewBox= "0 0 16 16" >
< path d= "M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
< /svg>
< /button>
< button type= "button" class = "btn btn-light"
@ click= "sortResult('DepartmentName',false)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-arrow-up-square-fill" viewBox= "0 0 16 16" >
< path d= "M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
< /svg>
< /button>
< /div>
DepartmentName
< /th>
< th>
Options
< /th>
< /tr>
< /thead>
< tbody>
< tr v- for = "dep in departments" >
< td> {{dep.DepartmentId}}< /td>
< td> {{dep.DepartmentName}}< /td>
< td>
< button type= "button"
class = "btn btn-light mr-1"
data- bs- toggle= "modal"
data- bs- target= "#exampleModal"
@ click= "editClick(dep)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-pencil-square" viewBox= "0 0 16 16" >
< path d= "M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
< path fill- rule= "evenodd" d= "M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
< /svg>
< /button>
< button type= "button" @ click= "deleteClick(dep.DepartmentId)"
class = "btn btn-light mr-1" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-trash-fill" viewBox= "0 0 16 16" >
< path d= "M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z" />
< /svg>
< /button>
< /td>
< /tr>
< /tbody>
< /thead>
< /table>
< div class = "modal fade" id= "exampleModal" tabindex= "-1"
aria- labelledby= "exampleModalLabel" aria- hidden= "true" >
< div class = "modal-dialog modal-lg modal-dialog-centered" >
< div class = "modal-content" >
< div class = "modal-header" >
< h5 class = "modal-title" id= "exampleModalLabel" > {{modalTitle}}< /h5>
< button type= "button" class = "btn-close" data- bs- dismiss= "modal"
aria- label= "Close" >< /button>
< /div>
< div class = "modal-body" >
< div class = "input-group mb-3" >
< span class = "input-group-text" > Department Name< /span>
< input type= "text" class = "form-control" v- model= "DepartmentName" >
< /div>
< button type= "button" @ click= "createClick()"
v- if = "DepartmentId==0" class = "btn btn-primary" >
Create
< /button>
< button type= "button" @ click= "updateClick()"
v- if = "DepartmentId!=0" class = "btn btn-primary" >
Update
< /button>
< /div>
< /div>
< /div>
< /div>
< /div>
` ,
data(){
return {
departments: [],
modalTitle: "" ,
DepartmentName: "" ,
DepartmentId: 0 ,
DepartmentNameFilter: "" ,
DepartmentIdFilter: "" ,
departmentsWithoutFilter: []
}
},
methods: {
refreshData(){
axios.get(variables.API_URL+ "department" )
.then((response)=> {
this .departments= response.data;
this .departmentsWithoutFilter= response.data;
});
},
addClick(){
this .modalTitle= "Add Department" ;
this .DepartmentId= 0 ;
this .DepartmentName= "" ;
},
editClick(dep){
this .modalTitle= "Edit Department" ;
this .DepartmentId= dep.DepartmentId;
this .DepartmentName= dep.DepartmentName;
},
createClick(){
axios.post(variables.API_URL+ "department" ,{
DepartmentName: this .DepartmentName
})
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
updateClick(){
axios.put(variables.API_URL+ "department" ,{
DepartmentId: this .DepartmentId,
DepartmentName: this .DepartmentName
})
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
deleteClick(id){
if (! confirm("Are you sure?" )){
return ;
}
axios.delete (variables.API_URL+ "department/" + id)
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
FilterFn(){
var DepartmentIdFilter= this .DepartmentIdFilter;
var DepartmentNameFilter= this .DepartmentNameFilter;
this .departments= this .departmentsWithoutFilter.filter(
function (el){
return el.DepartmentId.toString().toLowerCase().includes(
DepartmentIdFilter.toString().trim().toLowerCase()
)&&
el.DepartmentName.toString().toLowerCase().includes(
DepartmentNameFilter.toString().trim().toLowerCase()
)
});
},
sortResult(prop,asc){
this .departments= this .departmentsWithoutFilter.sort(function (a,b){
if (asc){
return (a[prop]> b[prop])? 1 : ((a[prop]< b[prop])?- 1 : 0 );
}
else {
return (b[prop]> a[prop])? 1 : ((b[prop]< a[prop])?- 1 : 0 );
}
})
}
},
mounted: function (){
this .refreshData();
}
}
employee.js:
const employee= {template: `
< div>
< button type= "button"
class = "btn btn-primary m-2 fload-end"
data- bs- toggle= "modal"
data- bs- target= "#exampleModal"
@ click= "addClick()" >
Add Employee
< /button>
< table class = "table table-striped" >
< thead>
< tr>
< th>
Employee Id
< /th>
< th>
Employee Name
< /th>
< th>
Department
< /th>
< th>
DOJ
< /th>
< th>
Options
< /th>
< /tr>
< /thead>
< tbody>
< tr v- for = "emp in employees" >
< td> {{emp.EmployeeId}}< /td>
< td> {{emp.EmployeeName}}< /td>
< td> {{emp.Department}}< /td>
< td> {{emp.DateOfJoining}}< /td>
< td>
< button type= "button"
class = "btn btn-light mr-1"
data- bs- toggle= "modal"
data- bs- target= "#exampleModal"
@ click= "editClick(emp)" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-pencil-square" viewBox= "0 0 16 16" >
< path d= "M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
< path fill- rule= "evenodd" d= "M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
< /svg>
< /button>
< button type= "button" @ click= "deleteClick(emp.EmployeeId)"
class = "btn btn-light mr-1" >
< svg xmlns= "http://www.w3.org/2000/svg" width= "16" height= "16" fill= "currentColor" class = "bi bi-trash-fill" viewBox= "0 0 16 16" >
< path d= "M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z" />
< /svg>
< /button>
< /td>
< /tr>
< /tbody>
< /thead>
< /table>
< div class = "modal fade" id= "exampleModal" tabindex= "-1"
aria- labelledby= "exampleModalLabel" aria- hidden= "true" >
< div class = "modal-dialog modal-lg modal-dialog-centered" >
< div class = "modal-content" >
< div class = "modal-header" >
< h5 class = "modal-title" id= "exampleModalLabel" > {{modalTitle}}< /h5>
< button type= "button" class = "btn-close" data- bs- dismiss= "modal"
aria- label= "Close" >< /button>
< /div>
< div class = "modal-body" >
< div class = "d-flex flex-row bd-highlight mb-3" >
< div class = "p-2 w-50 bd-highlight" >
< div class = "input-group mb-3" >
< span class = "input-group-text" > Name< /span>
< input type= "text" class = "form-control" v- model= "EmployeeName" >
< /div>
< div class = "input-group mb-3" >
< span class = "input-group-text" > Department< /span>
< select class = "form-select" v- model= "Department" >
< option v- for = "dep in departments" >
{{dep.DepartmentName}}
< /option>
< /select>
< /div>
< div class = "input-group mb-3" >
< span class = "input-group-text" > DOJ< /span>
< input type= "date" class = "form-control" v- model= "DateOfJoining" >
< /div>
< /div>
< div class = "p-2 w-50 bd-highlight" >
< img width= "250px" height= "250px"
: src= "PhotoPath+PhotoFileName" />
< input class = "m-2" type= "file" @ change= "imageUpload" >
< /div>
< /div>
< button type= "button" @ click= "createClick()"
v- if = "EmployeeId==0" class = "btn btn-primary" >
Create
< /button>
< button type= "button" @ click= "updateClick()"
v- if = "EmployeeId!=0" class = "btn btn-primary" >
Update
< /button>
< /div>
< /div>
< /div>
< /div>
< /div>
` ,
data(){
return {
departments: [],
employees: [],
modalTitle: "" ,
EmplpoyeeId: 0 ,
EmployeeName: "" ,
Department: "" ,
DateOfJoining: "" ,
PhotoFileName: "anonymous.png" ,
PhotoPath: variables.PHOTO_URL
}
},
methods: {
refreshData(){
axios.get(variables.API_URL+ "employee" )
.then((response)=> {
this .employees= response.data;
});
axios.get(variables.API_URL+ "department" )
.then((response)=> {
this .departments= response.data;
});
},
addClick(){
this .modalTitle= "Add Employee" ;
this .EmployeeId= 0 ;
this .EmployeeName= "" ;
this .Department= "" ,
this .DateOfJoining= "" ,
this .PhotoFileName= "anonymous.png"
},
editClick(emp){
this .modalTitle= "Edit Employee" ;
this .EmployeeId= emp.EmployeeId;
this .EmployeeName= emp.EmployeeName;
this .Department= emp.Department,
this .DateOfJoining= emp.DateOfJoining,
this .PhotoFileName= emp.PhotoFileName
},
createClick(){
axios.post(variables.API_URL+ "employee" ,{
EmployeeName: this .EmployeeName,
Department: this .Department,
DateOfJoining: this .DateOfJoining,
PhotoFileName: this .PhotoFileName
})
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
updateClick(){
axios.put(variables.API_URL+ "employee" ,{
EmployeeId: this .EmployeeId,
EmployeeName: this .EmployeeName,
Department: this .Department,
DateOfJoining: this .DateOfJoining,
PhotoFileName: this .PhotoFileName
})
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
deleteClick(id){
if (! confirm("Are you sure?" )){
return ;
}
axios.delete (variables.API_URL+ "employee/" + id)
.then((response)=> {
this .refreshData();
alert(response.data);
});
},
imageUpload(event){
let formData= new FormData();
formData.append('file' ,event.target.files[0 ]);
axios.post(
variables.API_URL+ "employee/savefile" ,
formData)
.then((response)=> {
this .PhotoFileName= response.data;
});
}
},
mounted: function (){
this .refreshData();
}
}
home.js:
const home= {template: ` < h1> This is Home< /h1>`}
variables.js:
const variables= {
API_URL: "http://localhost:49146/api/" ,
PHOTO_URL: "http://localhost:49146/photos/"
}