Tutorial on Hotel-Management-System using Django Framework

Foluke Akpobasa
5 min readSep 19, 2021

--

This tutorial will guide you through the creation of a web application for a Hotel Management System using the Django framework.

Features of the Hotel Management System

  • Login Signup for both users, superuser and staffs.
  • Logout feature for both users, superuser and staffs.
  • Adding, deleting, and updating rooms by the receptionist.
  • User booking details can be viewed by the receptionist
  • Superuser gain access to every functionality available in the app.
  • Make Booking
  • Make Payment after booking

To create a Django Hotel Management System, we must have Visual studio code or any other django supporting platform IDE and its requirements Installed on our computer.

Launch your IDE

Open terminal or press cmd + j — this command opens the terminal in Vscode environment

Create and activate a virtual environment, enter these code on your terminal

>>>> python3 -m venv venv

>>>> source venv/bin/activate

Installing app dependency

>>>>python -m pip install Django

>>>>pip install psycopg2-binary==2.9.1

You may need to update pip first, if outdated

Creating project (base) directory

>>>> django-admin startproject hotel_management

Creating app

>>>> django-admin startapp hsm

Setting up Database

To alter the database setting, open Setting.py module. The default database setting is SQLite, no need of changing it, we are using SQLite.

DATABASES = {

‘default’: {

‘ENGINE’: ‘django.db.backends.sqlite3’,

‘NAME’: BASE_DIR / ‘db.sqlite3’,

}

}

Create models

To create models, go to models.py, import these module.

from django.db import models

from django.db.models.deletion import CASCADE

import uuid

Enter the following code snippets to create model for Users, Receptionist, RoomType, Room, RoomStatus, PaymentType, Payment, Booking

class User(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

username = models.CharField(max_length=30, unique=True)

email = models.EmailField(max_length=254, unique=True)

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

password = models.CharField(max_length=20)

otp_code = models.CharField(max_length=6, unique=True, null=True)

email_verified = models.BooleanField(default=False)

is_admin = models.BooleanField(default=False)

is_superadmin = models.BooleanField(default=False)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return self.username

class Receptionist(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

user_id = models.ForeignKey(User, on_delete=models.CASCADE)

first_name = models.CharField(max_length=25)

last_name = models.CharField(max_length=25)

gender = models.CharField(max_length=6)

avatar_url = models.CharField(max_length=260, null=True)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Receptionist {self.first_name} {self.last_name}’

class RoomType(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

type = models.CharField(max_length=30, unique=True)

price = models.CharField(max_length=10)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Room {self.type} price: {self.price}’

class RoomStatus(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

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

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Room {self.status}’

class Room(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

room_type_id = models.ForeignKey(RoomType, on_delete=models.CASCADE)

room_status_id = models.ForeignKey(RoomStatus, on_delete=models.CASCADE)

room_no = models.CharField(max_length=5, unique=True)

price = models.CharField(max_length=10)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Room {self.room_no} price:{self.price} is currently {self.room_status_id}’

class PaymentType(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

name = models.CharField(max_length=30, unique=True)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Payment option {self.name}’

class Payment(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

payment_type_id = models.ForeignKey(PaymentType, on_delete=models.CASCADE)

customer_id = models.ForeignKey(User, on_delete=CASCADE)

staff_id = models.ForeignKey(Receptionist, on_delete=CASCADE)

amount = models.CharField(max_length=10)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Customer {self.customer_id} amount:{self.amount} processed by staff {self.staff_id}’

class Booking(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

room_id = models.ForeignKey(Room, on_delete=models.CASCADE)

customer_id = models.ForeignKey(User, on_delete=CASCADE)

staff_id = models.ForeignKey(Receptionist, on_delete=CASCADE)

payment_id = models.ForeignKey(Payment, on_delete=models.CASCADE)

created_at = models.DateTimeField(auto_now_add=True, null=True)

updated_at = models.DateTimeField(auto_now=True, null=True)

def __str__(self):

return f’Booking by customer {self.customer_id} paid {self.payment_id} for room {self.room_id}’

Run migrations

Now that we have created the models, we can now apply migrations. Add the database information to settings.py

>>>>python3 manage.py makemigration

>>>>python3 manage.py migrates

Running the app

While in base directory that contains manage.py , onn the terminal enter

>>>>python manage.py runserver

Creating template

In the app directory create a directory called “template”. This is where all template to be rendered will be stored.

create a file, “login.html”

{% extends ‘hotel/base.html’ %}

{% load crispy_forms_tags %}

{% block content %}

<div class=”content-section” >

<form method=”POST”>

{% csrf_token %}

<fieldset class=”form-group” >

<legend class=”border-bottom mb-4" >

Join Today

</legend>

{{form| crispy}}

</fieldset>

<div class=”form-group” >

<button class=”btn btn-outline-info” type=”submit”> Sign Up</button>

</div>

</form>

<div class=”border-top pt-3">

<small class=”text-muted”>

Already have an account? <a href=”#” class=”ml-2"> Sign In</a>

</small>

</div>

</div>

{% endblock content%}

Writing view for the app

Let’s now bulid the logic for our app. In view.py enter these lines of code

from django.http import HttpResponse

from django.shortcuts import render, redirect, get_object_or_404

from django.contrib import messages

from hotel.forms import UserRegisterForm, ReceptionistRegisterForm

from django.contrib.auth.decorators import login_required

from django.contrib.auth import authenticate, login

from django import forms

from .models import User, Receptionist,Room,RoomStatus,RoomType

def homepage(request):

return render(request,’hotel/index.html’)

def about(request):

return render(request,’hotel/about.html’)

room_types = RoomType.objects.all()

room = Room.objects.all()

room_status = RoomStatus.objects.all()

context = {‘rooms’: room_types,’room_status’:room_status,’room_no’:room}

def rooms(request):

return render(request, ‘hotel/rooms.html’, context)

def rooms_detailed_view(request, room_id):

room_detail = get_object_or_404(RoomType, pk=room_id)

return render(request, ‘hotel/rooms_views.html’,{‘room’: room_detail,’rooms’: room_types,’room_no’:room})

def booking(request,room_id):

room_detail = get_object_or_404(RoomType, pk=room_id)

return render(request, ‘hotel/booking.html’,{‘room’: room_detail,’rooms’: room_types,’room_no’:room})

# payment

def payment(request,room_id):

room_detail = get_object_or_404(RoomType, pk=room_id)

return render(request, ‘hotel/payment.html’,{‘room’: room_detail,’rooms’: room_types,’room_no’:room})

# authorization and authentication

def admin_create(request):

if request.method == “POST”:

form = UserRegisterForm(request.POST)

if form.is_valid():

form.save()

username = form.cleaned_data.get(‘username’)

messages.success(request, “Your account has been created successfully! You are now able to log in”)

return redirect(‘admin-login’)

else:

form = UserRegisterForm()

return render(request, ‘hotel/register.html’, {‘form’: form})

def register_receptionist(request):

if request.method == “POST”:

form = ReceptionistRegisterForm(request.POST)

if form.is_valid():

form.save()

first_name = form.cleaned_data.get(‘first_name’)

messages.success(request, “Your account has been created successfully as a Receptionist! You are now able to log in”)

return redirect(‘admin-login’)

else:

form = ReceptionistRegisterForm()

return render(request, ‘hotel/register_Reception.html’, {‘form’: form})

@login_required

def profile(request):

return render(request, ‘hotel/profile.html’)

@login_required

def dashboard(request):

return render(request, ‘hotel/dashboard.html’, {‘dash’: ‘This is the dashboard’})

def admin_list(request):

hotel_admin_list = User.objects.all()

return render(request, ‘hotel/admin_list.html’, {‘admin_lists’: hotel_admin_list})

def show_admin(request, uuid):

display_admin = Receptionist.objects.get(uuid(uuid))

return render(request, ‘hotel/show_admin.html’, {‘show_admin’: display_admin})

Creating the route for the app

Go to url.py, enter these code

from django.urls import path

from django.contrib.auth import views as auth_views

from . import views

from . import views as users_views

urlpatterns = [

# path(‘/rooms/<uuid:room_id>/booking/payment’,views.payment, name = ‘payment’),

# path(‘/rooms/<uuid:room_id>/checkin’,views.room_checkin, name = ‘room_checkin’),

# path(‘/rooms/<uuid:room_id>/checkout’,views.room_checkout, name = ‘room_checkout’),

path(‘rooms/’, views.rooms, name=’rooms’),

path(‘rooms/<uuid:room_id>/’, views.rooms_detailed_view, name=’rooms_detailed_view’),

path(‘rooms/<uuid:room_id>/booking/’, views.booking, name=’booking’),

# payment

path(‘rooms/<uuid:room_id>/booking/payment/’, views.payment, name=’payment’),

path(‘’, views.homepage, name=’hotel-home’),

path(‘about/’, views.about, name=’hotel-about’),

path(‘dashboard’, views.dashboard, name=’dashboard’),

path(‘admin’, views.admin_list, name=’admin-list’),

path(‘admin/create’, users_views.admin_create, name=’register’),

path(‘profile/’, users_views.profile, name=’profile’),

path(‘/admin/create’, views.admin_create, name=’admin-create’),

path(‘/admin/<uuid:staff_id>’, views.show_admin, name= ‘admin-staff’),

path(‘/admin/<uuid:staff_id>/edit’, views.edit_admin, name= ‘admin-staff-edit’),

path(‘/admin/<uuid:staff_id>/delete’, views.delete_admin, name=’admin-staff-delete’),

path(‘login’, auth_views.LoginView.as_view(template_name = ‘hotel/login.html’), name= ‘admin-login’),

path(‘logout’, auth_views.LogoutView.as_view(template_name= ‘hotel/logout.html’), name= ‘admin-logout’),

# addition

path(‘/admin/logs’,views.logs, name = ‘logs’)

]

Deployement to Heroko

CONTINUOUS DEPLOYMENT (CD) USING HEROKU,

1. initialise a git repo in your root directory

do either from CLI or heroku platform

2. install heroku, homebrew: brew tap heroku/brew && brew install heroku

3. login/ create account on heroku

4. create heroku app

5. connect the heroku remote to your git remote: by default heroku takes build from the main branch of your git repo

heroku git:remote -a <heroku_app_name>

heroku git:remote -a immense-shelf-79091

6. update your main branch: git add -A, git add . , git commit -m

push to remote main: git push origin main

7. install gunicorn and whitenoise as dependencies

gunicorn : helps heroku to serve your app to the internet working with your wsgi.py file

--

--