Mastering Django Forms add/view Data : A Comprehensive Guide

Codes With Pankaj
4 min readFeb 14, 2024

Django, with its robust framework, offers a powerful toolset for building web applications efficiently. Among its many features, Django forms stand out as a fundamental component for handling user input. In this guide, we’ll delve into Django forms, exploring their significance, implementation, customization, and best practices to empower you in mastering this essential aspect of Django development.

Understanding Django Forms: At its core, a Django form is a mechanism for collecting and processing user data. Whether it’s a simple contact form or a complex multi-step wizard, Django forms provide a structured way to handle user input and perform validations.

Step 1 : Set up a Django project

  1. Open your terminal or command prompt.
  2. Navigate to the directory where you want to create your project.
  3. Run the following command to create a new Django project named “p4n_form”:
django-admin startproject p4n_form

4. Navigate into the project directory:

cd p4n_form

Step 2 : Create a Django app

  1. Inside the project directory, create a new Django app named “employee”:
python manage.py startapp employee

2. Open the p4n_form/settings.py file and add 'employee', to the INSTALLED_APPS list.

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

Step 3 : Define the Employee model

  1. Open the employee/models.py file and define the Employee model to represent employee information. For example:
# @codeswithpankaj.com
from django.db import models

class Employee(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
phone_number = models.CharField(max_length=15)

2. Open the employee/admin.py file and register the Employee model.

# @codeswithpankaj.com
from django.contrib import admin
from .models import Employee

admin.site.register(Employee)

Step 4 : Create a form for employee information

  1. Create a new file named forms.py inside the employee app directory.
# @codeswithpankaj.com
from django import forms
from .models import Employee

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

Step 5 : Create a view for the form

  1. Open the employee/views.py file and define a view for rendering the form.
# @codeswithpankaj.com
from django.shortcuts import render
from .forms import EmployeeForm
from .models import Employee

def employee_form(request):
if request.method == 'POST':
form = EmployeeForm(request.POST)
if form.is_valid():
form.save()
# Redirect to a success page or do something else
else:
form = EmployeeForm()
return render(request, 'employee_form.html', {'form': form})

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

Step 6 : Create a template for the form and View Data

  1. Create a directory named templates inside the employee app directory if it doesn't already exist.
  2. Inside the templates directory, create a new file named employee_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee Form</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Optional Bootstrap theme -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap-theme.min.css">
<style>
/* Custom CSS for adjusting label width */
.form-group label {
width: 150px; /* Adjust as needed */
text-align: right;
margin-bottom: 0;
padding-right: 10px;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-header bg-primary text-white">
<h1 class="text-center">Employee Form</h1>
</div>
<div class="card-body">
<form method="post">
{% csrf_token %}
<div class="form-group row">
<label for="id_first_name" class="col-sm-4 col-form-label">First Name:</label>
<div class="col-sm-8">
{{ form.first_name }}
</div>
</div>
<div class="form-group row">
<label for="id_last_name" class="col-sm-4 col-form-label">Last Name:</label>
<div class="col-sm-8">
{{ form.last_name }}
</div>
</div>
<div class="form-group row">
<label for="id_email" class="col-sm-4 col-form-label">Email:</label>
<div class="col-sm-8">
{{ form.email }}
</div>
</div>
<div class="form-group row">
<label for="id_phone_number" class="col-sm-4 col-form-label">Phone Number:</label>
<div class="col-sm-8">
{{ form.phone_number }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
</form>
<br>
<a href="{% url 'employee_list' %}"><button>View Employee Data</button></a>
</div>
</div>
</div>
</div>
</div>

<!-- Footer -->
<footer class="footer mt-auto py-3 bg-light">
<div class="container text-center">
<span class="text-muted">Designed with love by <a href="https://codeswithpankaj.com" target="_blank">Codes with Pankaj</a></span>
</div>
</footer>

<!-- Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

Create a new HTML file named employee_list.html inside the employee/templates directory.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee List</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
padding-top: 5rem;
background-color: #f4f4f4;
}
footer {
position: fixed;
bottom: 0;
width: 100%;
height: 3rem;
line-height: 3rem;
background-color: #f8f9fa;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="#">Employee List</a>
</nav>

<div class="container mt-5">
<a href="{% url 'employee_form' %}"><button>Add New Employee</button></a>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone Number</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.phone_number }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>

<footer class="text-center">
<p>Designed and Developed by <a href="https://codeswithpankaj.com">CodesWithPankaj</a></p>
</footer>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

Step 7 : Define URLs

  1. Open the employee/urls.py file and define a URL pattern for the form view.
# @codeswithpankaj.com
from django.urls import path
from . import views

urlpatterns = [
path('form/', views.employee_form, name='employee_form'),
path('list/', views.employee_list, name='employee_list'),
]

2. Include the app’s URLs in the project’s URL configuration. Open p4n_form/urls.py and include the employee app's URLs.

# @codeswithpankaj.com
from django.contrib import admin
from django.urls import path, include

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

Step 8 : Run migrations to apply

Run migrations to apply the model changes to the database :

python manage.py makemigrations
python manage.py migrate

Step 9 : Create a superuser

Run the following command

python manage.py createsuperuser

Follow the prompts to create a superuser account. You’ll be asked for a username, email (optional), and password.

Step 10 : Run the server

Start the development server by running the following command

python manage.py runserver
  1. Open a web browser and go to http://127.0.0.1:8000/admin.
  2. Log in with the superuser credentials you created earlier.
  3. You should now see the Django admin interface.
  4. Navigate to the “Employees” section to manage employee records.

That’s it! You’ve added the admin interface, created a superuser, and started the development server for your Django project. You can now manage employee records through the admin interface and access the employee form at http://127.0.0.1:8000/employee/form/.

Display employee data. You can access it at http://127.0.0.1:8000/employee/list/. This view will list all employees stored in the database.

Download Complete Project Code —

--

--