Create Human Resource Management System in Django

Faraz

By Faraz - September 08, 2024

Learn how to build a Human Resource Management System in Django with this step-by-step guide.


create-human-resource-management-system-in-django.webp

Creating a Human Resource Management System (HRMS) in Django is a great way to manage employee data, track performance, and streamline HR processes. This guide will walk you through the steps to build a simple yet effective HRMS using Django, a popular web framework for Python. Whether you're a beginner or an experienced developer, this tutorial will help you create a functional HRMS with ease.

Prerequisites

Before we dive in, make sure you have a basic understanding of Django and web development. You'll need the following tools and libraries installed on your machine:

  • Python (version 3.6 or higher)
  • Django (version 3.0 or higher)
  • A text editor or IDE (such as VS Code or PyCharm)
  • Basic knowledge of HTML and CSS

Setting Up the Development Environment

1. Setup Environment

Before you start coding, you need to set up your development environment. Here’s how:

  • Install Python: Ensure Python is installed on your system. You can download it from python.org.
  • Install Django: Open your command prompt or terminal and install Django using pip:
    pip install django
  • Create a Project Directory: Make a new directory for your project and navigate into it:
    mkdir hrms_django
    	cd hrms_django

2. Create a Django Projec

Start by creating a new Django project:

django-admin startproject hrms
cd hrms

3. Create a Django App

Within your project, create a new app to handle the HRMS features:

python manage.py startapp employee

4. Adding the app to the project

In hrms/settings.py, add employee to the INSTALLED_APPS list:

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

Creating the Human Resource Management System App

1. Create Models

Define your models for Employee and LeaveRequest in employee/models.py. These models will represent the data in your HRMS.

from django.db import models
from django.utils import timezone

class Employee(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()
    department = models.CharField(max_length=100)
    position = models.CharField(max_length=100)
    hire_date = models.DateField() #2024-09-08
    resignation_date = models.DateField(null=True, blank=True) #2024-09-08

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

class LeaveRequest(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_type = models.CharField(max_length=50)
    start_date = models.DateField()
    end_date = models.DateField() #2024-09-08
    reason = models.TextField()
    status = models.CharField(max_length=20, default='Pending')

    def __str__(self):
        return f"{self.employee} - {self.leave_type}"

2. Create Forms

In employee, create a new file named forms.py to handle employee and leave request data:

from django import forms
from .models import Employee, LeaveRequest

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = ['first_name', 'last_name', 'email', 'department', 'position', 'hire_date', 'resignation_date']

class LeaveRequestForm(forms.ModelForm):
    class Meta:
        model = LeaveRequest
        fields = ['employee', 'leave_type', 'start_date', 'end_date', 'reason']

3. Create Views

Next, we’ll create views to render the templates and handle data. Open employee/views.py and add the following:

from django.shortcuts import render, redirect, get_object_or_404
from .models import Employee, LeaveRequest
from .forms import EmployeeForm, LeaveRequestForm

def employee_list(request):
    employees = Employee.objects.all()
    return render(request, 'employee_list.html', {'employees': employees})

def employee_add(request):
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('employee_list')
    else:
        form = EmployeeForm()
    return render(request, 'employee_form.html', {'form': form})

def employee_edit(request, pk):
    employee = get_object_or_404(Employee, pk=pk)
    if request.method == 'POST':
        form = EmployeeForm(request.POST, instance=employee)
        if form.is_valid():
            form.save()
            return redirect('employee_list')
    else:
        form = EmployeeForm(instance=employee)
    return render(request, 'employee_form.html', {'form': form})

def leave_request_list(request):
    leave_requests = LeaveRequest.objects.all()
    return render(request, 'leave_request_list.html', {'leave_requests': leave_requests})

def leave_request_add(request):
    if request.method == 'POST':
        form = LeaveRequestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('leave_request_list')
    else:
        form = LeaveRequestForm()
    return render(request, 'leave_request_form.html', {'form': form})

4. Create Templates

Create a templates directory within the Employee app and then create base.html, employee_list.html, employee_form.html, leave_request_list.html and leave_request_form.html inside this directory.

base.html

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}HRMS{% endblock %}</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="{% static 'styles/custom.css' %}">
    {% block extra_head %}{% endblock %}
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="{% url 'employee_list' %}">HRMS</a>
        <div class="collapse navbar-collapse">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'employee_list' %}">Employees</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'leave_request_list' %}">Leave Requests</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container">
        {% block content %}{% endblock %}
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    {% block extra_scripts %}{% endblock %}
</body>
</html>

employee_list.html

{% extends 'base.html' %}

{% block title %}Employee List{% endblock %}
{% block content %}

    <h1 class="my-4">Employee List</h1>
    <a href="{% url 'employee_add' %}" class="btn btn-success mb-3">Add New Employee</a>
    <table class="table table-striped table-bordered">
        <thead class="thead-dark">
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Department</th>
                <th>Position</th>
                <th>Hire Date</th>
                <th>Resignation Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for employee in employees %}
                <tr>
                    <td>{{ employee.first_name }}</td>
                    <td>{{ employee.last_name }}</td>
                    <td>{{ employee.email }}</td>
                    <td>{{ employee.department }}</td>
                    <td>{{ employee.position }}</td>
                    <td>{{ employee.hire_date }}</td>
                    <td>{{ employee.resignation_date }}</td>
                    <td>
                        <a href="{% url 'employee_edit' employee.pk %}" class="btn btn-warning btn-sm">Edit</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}

employee_form.html

{% extends 'base.html' %}

{% block title %}{% if form.instance.pk %}Edit{% else %}Add{% endif %} Employee{% endblock %}

{% block content %}
    <h1 class="my-4">{% if form.instance.pk %}Edit{% else %}Add{% endif %} Employee</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
{% endblock %}

leave_request_list.html

{% extends 'base.html' %}

{% block title %}Leave Requests{% endblock %}

{% block content %}
    <h1 class="my-4">Leave Requests</h1>
    <a href="{% url 'leave_request_add' %}" class="btn btn-success mb-3">Add New Leave Request</a>
    <table class="table table-striped table-bordered">
        <thead class="thead-dark">
            <tr>
                <th>Employee</th>
                <th>Leave Type</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Reason</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            {% for leave_request in leave_requests %}
                <tr>
                    <td>{{ leave_request.employee }}</td>
                    <td>{{ leave_request.leave_type }}</td>
                    <td>{{ leave_request.start_date }}</td>
                    <td>{{ leave_request.end_date }}</td>
                    <td>{{ leave_request.reason }}</td>
                    <td>{{ leave_request.status }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}

leave_request_form.html

{% extends 'base.html' %}

{% block title %}Add Leave Request{% endblock %}

{% block content %}
    <h1 class="my-4">Add Leave Request</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
{% endblock %}

5. Set Up URL Routing

Add a URL pattern for your view. In employee/urls.py (create this file if it doesn't exist), add:

from django.urls import path
from .views import employee_list, employee_add, employee_edit, leave_request_list, leave_request_add

urlpatterns = [
    path('', employee_list, name='employee_list'),
    path('add/', employee_add, name='employee_add'),
    path('edit//', employee_edit, name='employee_edit'),
    path('leave-requests/', leave_request_list, name='leave_request_list'),
    path('leave-requests/add/', leave_request_add, name='leave_request_add'),
]

Include the app's URLs in your project's URL configuration. Open hrms/urls.py and include the human resource management system app URLs:

from django.contrib import admin
from django.urls import path, include

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

Run Your Server

1. Run Migrations

Run migrations to update the database schema:

python manage.py makemigrations
python manage.py migrate

2. Start the Development Server

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/ to see your human resource management system app in action.

Full Human Resource Management System App Project Structure

hrms/
│
├── hrms/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
│
├── employee/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   ├── views.py
│   ├── migrations/
│   │   └── __init__.py
│   └── templates/
│           ├── base.html
│           ├── employee_list.html
│           ├── employee_form.html
│           ├── leave_request_list.html
│           └── leave_request_form.html
└── manage.py

Conclusion

With this guide, you’ve successfully created a Human Resource Management System in Django, featuring essential functions like adding and editing employees, managing leave requests, and handling resignation dates. By using a base HTML template, you’ve ensured a modern and consistent UI across your application. Keep refining and adding features to tailor the system to your specific needs.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺