jkisolo.com

Enhancing Data Management in Django HRMS: Update Functionality

Written on

Chapter 1: Implementing the Update Functionality

In our ongoing development of a straightforward Human Resource Management System (HRMS), the next critical step involves updating existing data records. Following our previous post where we discussed adding data, updating employee information should be relatively straightforward.

Handling the Backend Logic

To initiate the update process, we first address the backend logic responsible for executing the updates. The primary distinction between adding and updating an employee lies in the SQL query utilized.

For the add_employee function, we previously used the following SQL command:

insert_sql = f"""

INSERT INTO "HRMS_Employee" (employee_id, name, gender,

birthday, mobile, email, address)

VALUES ('{employee_id}', '{name}', '{gender}', '{birthday}', '{mobile}',

'{email}', '{address}')

"""

In contrast, the SQL statement for updating an employee record is structured as follows:

update_sql = f"""

UPDATE "HRMS_Employee" SET name = '{name}',

gender = '{gender}', birthday = '{birthday}',

mobile = '{mobile}', email = '{email}', address = '{address}'

WHERE employee_id = '{employee_id}'

"""

The remaining code can be repurposed from the add_employee function. We will now introduce an update_employee function in the apps/employee/views.py file:

def update_employee(request):

# 1. Retrieve information

employee_id = request.POST.get("id")

name = request.POST.get("name")

gender = request.POST.get("gender")

birthday = request.POST.get("birthday")

mobile = request.POST.get("mobile")

email = request.POST.get("email")

address = request.POST.get("address")

department_id = random.choice([1001, 1002, 1003, 1004, 1005, 1006])

# 2. Establish database connection

conn_info = settings.DATABASES["default"]

# 3. Create a PSQL connection instance

psql_conn = PSQLConn(conn_info)

# 4. Generate SQL command

sql = f"""

UPDATE "HRMS_Employee" SET name = '{name}', gender = '{gender}',

birthday = '{birthday}', mobile = '{mobile}', email = '{email}',

address = '{address}'

WHERE employee_id = '{employee_id}'

"""

# 5. Execute the update SQL command

psql_conn.update_db(sql)

# 6. Render results after updating

if psql_conn.flag:

# If SQL executes successfully, redirect

return redirect("/")

else:

# If SQL execution fails, show error

print(psql_conn.msg)

return render(request, "error.html", context={"msg": psql_conn.msg})

Next, we need to update the URL configuration in django_project/urls.py:

urlpatterns = [

path("", views.index), # Home page

path("employee/delete/", views.delete_employee), # Deletion URL

path("employee/add/", views.add_employee), # Adding URL

path("employee/update/", views.update_employee), # Updating URL

]

Preparing the Frontend

Similar to the addition logic, we will create a set of forms and JavaScript event handlers to capture user inputs for updating employee details. It's crucial to note that once an employee is assigned an ID, they cannot change it, which can be enforced by setting the readonly attribute.

We will implement a pop-up form that displays the selected employee's information when the user clicks the edit button. If the user chooses to cancel, the form will close. This requires modifications in the templates/index.html file, including:

{# Editing an Employee #}

<form id="editform">

{% csrf_token %}

ID: <input type="text" name="id" readonly>

Name: <input type="text" name="name">

Gender:

<select name="gender">

<option value="Female">Female</option>

<option value="Male">Male</option>

<option value="Other">Other</option>

</select>

Birthday: <input type="text" name="birthday">

Mobile: <input type="text" name="mobile">

Email: <input type="text" name="email">

Address: <input type="text" name="address">

</form>

We will also define JavaScript event handlers to manage the form's visibility and pre-fill it with the correct employee information:

// Event handler for editing an employee

$("table tbody tr").on("click", "#btnedit", function () {

$("#editform").fadeIn();

$("#editform input[name='id']").val($(this).children().eq(0).text());

$("#editform input[name='name']").val($(this).children().eq(1).text());

$("#editform select[name='gender']").val($(this).children().eq(2).text());

$("#editform input[name='birthday']").val($(this).children().eq(3).text());

$("#editform input[name='mobile']").val($(this).children().eq(4).text());

$("#editform input[name='email']").val($(this).children().eq(5).text());

$("#editform input[name='address']").val($(this).children().eq(6).text());

});

// Event handler to cancel editing

$("#edit_cancel").click(function () {

$("#editform").fadeOut();

});

When submitting the form, we must conduct validation checks before sending the updated data to the backend:

// Event handler for submitting the edit form

$("#editform").submit(function () {

// Validation checks...

let name = $("#editform input[name='name']").val().trim();

if (name.length === 0) {

alert("Name cannot be empty");

return false;

}

// Additional validation for gender, birthday, mobile, email, and address...

return true;

});

Once the data is validated, it will be sent to the /employee/update/ endpoint defined in the form.

Testing the Implementation

At this point, we can conduct tests to ensure that the update functionality operates as intended. A confirmation of the changes can be achieved through a SELECT query in the database.

In conclusion, we have successfully developed a fully functional HRMS system with complete CRUD capabilities. In our next installment, we will recap the v1 project and explore potential enhancements for v2.

Thank you for being a part of the In Plain English community!

Before you leave, consider following us on various platforms: X | LinkedIn | YouTube | Discord | Newsletter.

Explore our other ventures: Stackademic | CoFeed | Venture | Cubed.

More content can be found at PlainEnglish.io.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Stop Cutting the Feed: A Plea for Transparency in Space Exploration

A call for NASA to maintain uninterrupted feeds from the ISS, encouraging public engagement and transparency regarding potential UFO sightings.

Global Warming: The Urgency of Now and Its Impacts on Our Planet

An exploration of the alarming consequences of climate change, highlighting the urgent need for action to protect our planet.

# The Challenges of Online Education: Culture and Commitment

Exploring the obstacles online education faces in gaining widespread acceptance and effectiveness.

Embracing Unity Through Pickleball: A Path to Peace

Explore how Pickleball fosters unity and understanding among diverse individuals.

# Unlocking Your Potential: 10 Steps to Enhanced Effectiveness

Discover ten essential strategies to boost your effectiveness and productivity, fostering personal growth and fulfillment.

Finding Balance: The Art of Not Overvaluing or Undervaluing Life

Discover the importance of maintaining balance in emotions and life experiences to foster personal growth and well-being.

Experimenting with ChatGPT-Generated Trading Portfolios: Insights

A detailed update on the performance of ChatGPT-generated trading portfolios and insights gained from the experiment.

The Unbelievable Story of a Teen's Backyard Nuclear Reactor

A teenager's obsession leads to a backyard nuclear reactor, raising concerns about safety and oversight.