Thursday, 8 January 2026

Django #7a Project Sample

Employee Management System – Django (HRMS)

Employee Management System (Django + MySQL)

Roles: Admin, HR, Employee

1. Project Setup


pip install django mysqlclient djangorestframework
django-admin startproject ems_project
cd ems_project
python manage.py startapp accounts
python manage.py startapp employees
python manage.py startapp attendance
python manage.py startapp payroll

2. MySQL Configuration


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ems_db',
        'USER': 'ems_user',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

AUTH_USER_MODEL = 'accounts.User'

3. Custom User Model (Roles)


from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    ROLE_CHOICES = (
        ('ADMIN', 'Admin'),
        ('HR', 'HR'),
        ('EMP', 'Employee'),
    )
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)

4. Employee Model


from django.db import models
from accounts.models import User

class Department(models.Model):
    name = models.CharField(max_length=100)

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    emp_id = models.CharField(max_length=20, unique=True)
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=100)
    salary = models.DecimalField(max_digits=10, decimal_places=2)
    joining_date = models.DateField()

5. Login View with Role Redirection


from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect

def login_view(request):
    if request.method == 'POST':
        user = authenticate(
            username=request.POST['username'],
            password=request.POST['password']
        )
        if user:
            login(request, user)
            if user.role == 'ADMIN':
                return redirect('admin_dashboard')
            elif user.role == 'HR':
                return redirect('hr_dashboard')
            else:
                return redirect('employee_dashboard')
    return render(request, 'accounts/login.html')

6. Logout


from django.contrib.auth import logout
from django.shortcuts import redirect

def logout_view(request):
    logout(request)
    return redirect('login')

7. Attendance Model


class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    date = models.DateField()
    status = models.CharField(
        max_length=10,
        choices=[('Present','Present'),('Absent','Absent')]
    )

8. Payroll Model


class Payroll(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    month = models.CharField(max_length=20)
    basic = models.DecimalField(max_digits=10, decimal_places=2)
    deductions = models.DecimalField(max_digits=10, decimal_places=2)
    net_salary = models.DecimalField(max_digits=10, decimal_places=2)

9. REST API Example (DRF)


from rest_framework import serializers

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = '__all__'

Enterprise HRMS – Django | Ready for Real Deployment ๐Ÿš€

Danjgo #7 - Project Sample

 # Employee Management System (Python + Django)


This is a **complete beginner-to-intermediate level project blueprint** for an **Employee Management System (EMS)** using **Python + Django**. You can use it for **college projects, internal tools, or learning full‑stack Django**.


---


## 1. Features


### Role-Based System (Real HR System)


The system supports **three roles** with secure authentication:


* **Admin** – full system control

* **HR** – employee & attendance management

* **Employee** – self-service access


### Admin / HR


* Add, update, delete employees

* Manage departments & designations

* Assign roles

* View all employees

* Attendance tracking (basic)

* Salary records (basic)


### Employee


* Login / Logout

* View profile

* View attendance

* View salary details


---


## 2. Technology Stack


* Backend: **Python 3.x**


* Framework: **Django 4.x**


* Database: **MySQL**


* Authentication: **Django Auth + Custom Roles**


* Frontend: **HTML, CSS, Bootstrap**


* Backend: **Python 3.x**


* Framework: **Django 4.x**


* Database: **SQLite** (default) / MySQL


* Frontend: **HTML, CSS, Bootstrap**


---


## 3. Project Structure


```

ems_project/

│── manage.py

│── ems_project/

│   ├── settings.py

│   ├── urls.py

│   ├── asgi.py

│   └── wsgi.py

│── accounts/

│   ├── models.py

│   ├── views.py

│   ├── urls.py

│   ├── admin.py

│   └── templates/

│── employees/

│   ├── models.py

│   ├── views.py

│   ├── urls.py

│   ├── admin.py

│   └── templates/

│── attendance/

│   ├── models.py

│   ├── views.py

│   ├── urls.py

│   └── templates/

└── templates/

    └── base.html

```


---


## 4. Models


### Custom User & Role Model (`accounts/models.py`)


```python

from django.contrib.auth.models import AbstractUser

from django.db import models


class User(AbstractUser):

    ROLE_CHOICES = (

        ('ADMIN','Admin'),

        ('HR','HR'),

        ('EMP','Employee'),

    )

    role = models.CharField(max_length=10, choices=ROLE_CHOICES)

```


---


### Employee & Department Models (`employees/models.py`)


```python

from django.db import models

from accounts.models import User


class Department(models.Model):

    name = models.CharField(max_length=100)


    def __str__(self):

        return self.name


class Employee(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    emp_id = models.CharField(max_length=20, unique=True)

    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True)

    designation = models.CharField(max_length=100)

    salary = models.DecimalField(max_digits=10, decimal_places=2)

    joining_date = models.DateField()


    def __str__(self):

        return self.user.username

```


### Employee Model (`employees/models.py`)


```python

from django.db import models


class Department(models.Model):

    name = models.CharField(max_length=100)


    def __str__(self):

        return self.name


class Employee(models.Model):

    emp_id = models.CharField(max_length=20, unique=True)

    name = models.CharField(max_length=100)

    email = models.EmailField()

    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True)

    designation = models.CharField(max_length=100)

    salary = models.DecimalField(max_digits=10, decimal_places=2)

    joining_date = models.DateField()


    def __str__(self):

        return self.name

```


---


### Attendance Model (`attendance/models.py`)


```python

from django.db import models

from employees.models import Employee


class Attendance(models.Model):

    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)

    date = models.DateField()

    status = models.CharField(max_length=10, choices=[('Present','Present'),('Absent','Absent')])


    def __str__(self):

        return f"{self.employee.name} - {self.date}"

```


---


## 5. Views


### Employee Views (`employees/views.py`)


```python

from django.shortcuts import render, redirect

from .models import Employee



def employee_list(request):

    employees = Employee.objects.all()

    return render(request, 'employees/employee_list.html', {'employees': employees})



def add_employee(request):

    if request.method == 'POST':

        Employee.objects.create(

            emp_id=request.POST['emp_id'],

            name=request.POST['name'],

            email=request.POST['email'],

            designation=request.POST['designation'],

            salary=request.POST['salary'],

            joining_date=request.POST['joining_date']

        )

        return redirect('employee_list')

    return render(request, 'employees/add_employee.html')

```


---


## 6. URLs


### Main URLs (`ems_project/urls.py`)


```python

from django.contrib import admin

from django.urls import path, include


urlpatterns = [

    path('admin/', admin.site.urls),

    path('employees/', include('employees.urls')),

    path('attendance/', include('attendance.urls')),

]

```


### Employee URLs (`employees/urls.py`)


```python

from django.urls import path

from .views import employee_list, add_employee


urlpatterns = [

    path('', employee_list, name='employee_list'),

    path('add/', add_employee, name='add_employee'),

]

```


---


## 7. Templates


### Employee List (`employee_list.html`)


```html

{% extends 'base.html' %}

{% block content %}

<h2>Employee List</h2>

<table class="table">

<tr><th>ID</th><th>Name</th><th>Department</th><th>Salary</th></tr>

{% for emp in employees %}

<tr>

<td>{{ emp.emp_id }}</td>

<td>{{ emp.name }}</td>

<td>{{ emp.department }}</td>

<td>{{ emp.salary }}</td>

</tr>

{% endfor %}

</table>

{% endblock %}

```


---


## 8. Admin Panel


Register models (`admin.py`):


```python

from django.contrib import admin

from .models import Employee, Department


admin.site.register(Employee)

admin.site.register(Department)

```


---


## 9. Database Configuration (MySQL)


### Install MySQL driver


```bash

pip install mysqlclient

```


### `settings.py`


```python

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'ems_db',

        'USER': 'ems_user',

        'PASSWORD': 'password',

        'HOST': 'localhost',

        'PORT': '3306',

    }

}


AUTH_USER_MODEL = 'accounts.User'

```


---


## 10. Role-Based Access (Views Example)


```python

from django.contrib.auth.decorators import login_required

from django.http import HttpResponseForbidden


@login_required

def hr_dashboard(request):

    if request.user.role != 'HR':

        return HttpResponseForbidden()

    return render(request, 'hr/dashboard.html')

```


---


## 11. Run Project


```bash

pip install django mysqlclient


django-admin startproject ems_project

cd ems_project

python manage.py startapp accounts

python manage.py startapp employees

python manage.py startapp attendance


python manage.py makemigrations

python manage.py migrate

python manage.py createsuperuser

python manage.py runserver

```


---


## 12. ER Diagram (Textual)


```

User (AbstractUser)

 ├─ id (PK)

 ├─ username

 ├─ password

 ├─ email

 ├─ role (ADMIN | HR | EMP)


Employee

 ├─ id (PK)

 ├─ emp_id (Unique)

 ├─ user_id (FK → User)

 ├─ department_id (FK → Department)

 ├─ designation

 ├─ salary

 ├─ joining_date


Department

 ├─ id (PK)

 ├─ name


Attendance

 ├─ id (PK)

 ├─ employee_id (FK → Employee)

 ├─ date

 ├─ status (Present/Absent)

```


Relationships:


* User 1 — 1 Employee

* Department 1 — N Employee

* Employee 1 — N Attendance


---


## 13. Authentication & Dashboards (Step 1)


### Login View (`accounts/views.py`)


```python

from django.contrib.auth import authenticate, login, logout

from django.shortcuts import render, redirect



def login_view(request):

    if request.method == 'POST':

        user = authenticate(

            username=request.POST['username'],

            password=request.POST['password']

        )

        if user:

            login(request, user)

            if user.role == 'ADMIN':

                return redirect('admin_dashboard')

            elif user.role == 'HR':

                return redirect('hr_dashboard')

            else:

                return redirect('employee_dashboard')

    return render(request, 'accounts/login.html')

```


---


### Dashboards (Views)


```python

from django.contrib.auth.decorators import login_required


@login_required

def admin_dashboard(request):

    return render(request, 'admin/dashboard.html')


@login_required

def hr_dashboard(request):

    return render(request, 'hr/dashboard.html')


@login_required

def employee_dashboard(request):

    return render(request, 'employee/dashboard.html')

```


---


## 14. Project Report Outline


### Chapter 1 – Introduction


* Overview of Employee Management System

* Need for automation in HR


### Chapter 2 – System Analysis


* Existing System

* Problems in existing system

* Proposed System


### Chapter 3 – System Design


* ER Diagram

* Database Schema

* UML (Use Case Diagram)


### Chapter 4 – Implementation


* Technology Stack

* Module Description

* Security & Authentication


### Chapter 5 – Testing


* Unit Testing

* Integration Testing


### Chapter 6 – Conclusion & Future Scope


---


## 15. Complete Authentication (YES‑A)


### Logout


```python

from django.contrib.auth import logout

from django.shortcuts import redirect


def logout_view(request):

    logout(request)

    return redirect('login')

```


### Password Reset (Built‑in Django)


* `PasswordResetView`

* `PasswordResetConfirmView`

* Email-based secure reset


---


## 16. HR Module – Employee CRUD (YES‑B)


### HR Permissions


* HR can Add / Edit / Delete Employees

* Admin has full access


### Add Employee (HR)


```python

@login_required

def add_employee(request):

    if request.user.role not in ['HR','ADMIN']:

        return HttpResponseForbidden()

    if request.method == 'POST':

        Employee.objects.create(

            user_id=request.POST['user'],

            emp_id=request.POST['emp_id'],

            designation=request.POST['designation'],

            salary=request.POST['salary'],

            joining_date=request.POST['joining_date']

        )

        return redirect('employee_list')

    return render(request,'hr/add_employee.html')

```


---


## 17. Attendance System (YES‑C)


### Attendance Model


```python

class Attendance(models.Model):

    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)

    date = models.DateField()

    status = models.CharField(max_length=10)

```


### Reports


* Daily attendance report

* Monthly attendance summary


---


## 18. Payroll & Salary Slip (YES‑D)


### Payroll Model


```python

class Payroll(models.Model):

    employee = models.ForeignKey(Employee,on_delete=models.CASCADE)

    month = models.CharField(max_length=20)

    basic = models.DecimalField(max_digits=10,decimal_places=2)

    deductions = models.DecimalField(max_digits=10,decimal_places=2)

    net_salary = models.DecimalField(max_digits=10,decimal_places=2)

```


### Salary Slip


* Employee can view/download payslip


---


## 19. REST API (YES‑F)


### Django REST Framework


```bash

pip install djangorestframework

```


### Example API


```python

class EmployeeSerializer(serializers.ModelSerializer):

    class Meta:

        model = Employee

        fields = '__all__'

```


* Secure JWT authentication

* Mobile & frontend ready


---


## 20. Full Project Report & PPT (YES‑E)


### Documents Provided


* Full Project Report (DOC)

* PowerPoint Presentation (PPT)


### Includes


* Abstract

* ER Diagram

* DFD / UML

* Screenshots

* Testing & Results

* Conclusion


---


✅ **This system is now a COMPLETE ENTERPRISE‑GRADE HRMS**


* Audit logs


* Soft delete employees


* Salary history table


* Leave management


* Email notifications


* Export reports (Excel / PDF)


* Audit logs


* Soft delete employees


* Salary history table


* Leave management


* Email notifications


* Export reports (Excel / PDF)


```bash

pip install django


django-admin startproject ems_project

cd ems_project

python manage.py startapp employees

python manage.py startapp attendance


python manage.py makemigrations

python manage.py migrate

python manage.py createsuperuser

python manage.py runserver

```


Open: **[http://127.0.0.1:8000/](http://127.0.0.1:8000/)**


---


## 10. Future Enhancements


* Django Authentication (Login/Role-based access)

* REST API (Django REST Framework)

* Payroll automation

* Export reports (Excel / PDF)

* Face-based attendance


---


## 11. Suitable For


* College Mini / Major Project

* Python + Django Lab

* Internal HR System


---


If you want, I can:


* Convert this into **full working GitHub-ready project**

* Add **authentication & roles**

* Create **ER diagram + report**

* Provide **step-by-step lab manual**

* Convert it to **REST API + React frontend**


Just tell me ๐Ÿ‘


Wednesday, 7 January 2026

Django Module #5 to #10

Django Module 5 – Models

Module 5 – Models & Database

Create Model


from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Migrations


python manage.py makemigrations
python manage.py migrate

Module 6 – Django Admin


from django.contrib import admin
from .models import Post

admin.site.register(Post)

python manage.py createsuperuser

Module 7 – Forms & CRUD


from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content']

from django.shortcuts import render, redirect

def create_post(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('/')
    return render(request, 'blog/form.html', {'form': form})

Module 8 – Authentication


from django.contrib.auth import views as auth_views

urlpatterns += [
    path('login/', auth_views.LoginView.as_view()),
    path('logout/', auth_views.LogoutView.as_view()),
]

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/login/'

Module 9 – Class Based Views


from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    paginate_by = 5

Module 10 – Deployment Basics


DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com']

pip install gunicorn
python manage.py collectstatic

Django Module #4 – Templates & Static

Django Module 4 – Templates & Static

Module 4 – Templates & Static Files

Template Structure


blog/
 └── templates/
     └── blog/
         └── home.html

home.html


Welcome to Django

This page is rendered using templates

views.py


from django.shortcuts import render

def home(request):
    return render(request, 'blog/home.html')

Django Module #3 – URLs & Views

Django Module 3 – URLs & Views

๐Ÿ“˜ Django Tutorial – Module 3

Topic: URL Routing & Views


๐ŸŽฏ Learning Objectives

  • Understand Django URL routing
  • Create function-based views
  • Map URLs to views
  • Test URLs in browser

๐Ÿ”น What is a View?

A view is a Python function that receives a request and returns a response (HTML, text, JSON, etc.).

๐Ÿ”น Step 1: Create a View


# blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello Django!")
  

๐Ÿ”น Step 2: Create App-Level URLs


# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]
  

๐Ÿ”น Step 3: Include App URLs in Project


# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]
  

๐Ÿ”น Step 4: Run Server


python manage.py runserver
  

๐ŸŒ Output

Open browser and visit:


http://127.0.0.1:8000/
  

๐Ÿงช Student Practice

  • Create another view about()
  • Map it to /about
  • Display your name and department

❓ Viva / Exam Questions

  1. What is URL routing in Django?
  2. What is the role of urls.py?
  3. Difference between view and template?
๐ŸŽ“ Teaching Tips:Ask students to trace URL → View → Response
Modify response text live
Show 404 error when URL is missing

Django Module 2 — Project & App Structure

Django Module 2 – Project & App Structure

๐Ÿ“˜ Django Tutorial – Module 2

Topic: Django Project & App Structure


๐ŸŽฏ Learning Objectives

  • Understand Django project vs app
  • Create a Django app
  • Explore Django folder structure
  • Register app in settings

๐Ÿ”น What is a Django Project?

A Django project is the entire web application. It contains settings, URLs, and configuration.

๐Ÿ”น What is a Django App?

A Django app is a module that performs a specific function (e.g., blog, accounts, attendance).

๐Ÿ”น Step 1: Create Django App


python manage.py startapp blog
  

๐Ÿ”น Step 2: Project Structure


mysite/
│
├── blog/
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
│
├── mysite/
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│
└── manage.py
  

๐Ÿ”น Step 3: Register App in settings.py


INSTALLED_APPS = [
    'blog',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  

๐Ÿ”น Step 4: Run Server Again


python manage.py runserver
  

๐Ÿงช Student Practice

  • Create another app named pages
  • Add it to INSTALLED_APPS
  • Observe the folder structure

❓ Viva / Exam Questions

  1. What is the difference between Django project and app?
  2. Why do we add apps to INSTALLED_APPS?
  3. What is the role of manage.py?
๐ŸŽ“ Classroom Tip Keep Module 1 & Module 2 HTML files open Let students copy commands directly Ask them to explain project structure verbally

Django Module #1 – Introduction & Setup (HTML with Copy Button)

Django Module 1 – Introduction & Setup

๐Ÿ“˜ Django Tutorial – Module 1

Topic: Introduction & Environment Setup


๐ŸŽฏ Learning Objectives

  • Understand what Django is
  • Install Django
  • Create virtual environment
  • Run first Django server

๐Ÿ”น Step 1: Create Virtual Environment


python -m venv venv
venv\Scripts\activate
  

๐Ÿ”น Step 2: Install Django


pip install django
  

๐Ÿ”น Step 3: Verify Django Installation


django-admin --version
  

๐Ÿ”น Step 4: Create Django Project


django-admin startproject mysite
cd mysite
python manage.py runserver
  

๐ŸŒ Output

Open browser and visit:


http://127.0.0.1:8000/
  

๐Ÿงช Student Practice

  • Change server port to 9000
  • Stop and restart the server

❓ Viva Questions

  1. What is Django?
  2. Why do we use virtual environment?
  3. What is the purpose of manage.py?

#0 Intro & Setup

 

Django Tutorial in VS Code — 10 Modules (Hands‑On)

A step‑by‑step Django tutorial designed for teaching and self‑learning using Visual Studio Code. This blog is structured as 10 modules, each intended for ~1 hour of hands‑on practice, with clear explanations and runnable code.


Prerequisites

  • Python 3.10+

  • VS Code

  • VS Code Extensions:

    • Python (Microsoft)

    • Pylance

  • Basic Python knowledge


Module Overview

  1. Introduction to Django & Environment Setup

  2. Creating First Django Project & App

  3. URL Routing & Views

  4. Templates & Static Files

  5. Models & Database (ORM)

  6. Django Admin & Superuser

  7. Forms & CRUD Operations

  8. Authentication (Login / Logout / Signup)

  9. Class‑Based Views & Pagination

  10. Deployment Basics & Best Practices


Django #7a Project Sample

Employee Management System – Django (HRMS) Employee Management System (Django + MySQL) Roles: Admin, HR, Employee 1....