Library Management System In Python [Source Code Included]

Python Library Management System is important software which is used in the libraries of schools and colleges for adding new books in the library, issuing books to students and maintaining the record of the book that is returned.

About Library Management System

All the functions in the library are managed by the library management system. A person’s activities in the library can be automated with the help of this system. We will create a library management system that will handle various activities in a library. Let’s start developing this project.

Python Library Management System Project

In this project, we will develop a library management system that will help us in performing various functions like adding, issuing, and returning books. It will also store the issue and returning date of the book and the fine on the book if the book is not returned. Furthermore, the data of books that are stored can be edited and deleted. Installation of django is required before starting the project.

Project Prerequisites

Good knowledge of python and django framework is required to start the Library Management System Project. Basic knowledge of Html and CSS is also required to develop the frontend of the project.

Download Library Management System

Download source code of Library Management System: Python Library Management System Source Code 

Project File Structure

1. Installation of Django framework
2. Create a project and an app
3. Models.py
4. Admin.py
5. Urls.py
6. Views.py

1. Installation of Django framework:

The Django framework helps in rendering forms. This also validates data submitted by the user and it converts that data to python types. It is a high-level python web framework. It enables the development of secure websites.
Before starting the project, installation of django on your system is required. To install it on your system, write the following command on command prompt or terminal window.

pip install django

2. Create a project and an app:

After installing the django framework, create a project and an app . Here, we will create a project named TechVidvanLibrary and an app named home. Also, create a static folder to store images and all the css files. Create a templates folder to store all the html files. Run the following command on the terminal window to create a project folder and an app folder.

django -admin startproject TechVidvanLibrary
python manage.py startapp home

3. Models.py

Write the following code in models.py file in the home folder.

from django.db import models
from django.contrib.auth.models import User
from django.db.models.fields import CharField
from datetime import datetime,timedelta
class UserExtend(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    phone = models.IntegerField()
    def __str__(self):
       return self.user.username
class AddBook(models.Model):
    user = models.ForeignKey(User,default = 1, on_delete=models.CASCADE)
    bookid=CharField(max_length=10)
    bookname=CharField(max_length=50)
    subject=CharField(max_length=20)
    category= models.CharField(max_length = 10)
    def __str__(self):
        return str(self.bookname)+"["+str(self.bookid)+']'
def expiry():
    return datetime.today() + timedelta(days=15)
class IssueBook(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    studentid=CharField(max_length=20)
    book1=models.CharField(max_length=20)
    issuedate=models.DateField(auto_now=True)
    expirydate=models.DateField(default=expiry)
    def __str__(self):
        return self.studentid
class ReturnBook(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    bookid2=models.CharField(max_length=20)
class AddStudent(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    sname=models.CharField(max_length=30)
    studentid=models.CharField(max_length=20)
    def __str__(self):
        return self.sname+'['+str(self.studentid)+']'

Code Explanation:

Models.py file does the database connectivity.
a. UserExtend() model extends the user model as the user model contains only email, first name, last name and password. As we also want to save the phone number of a person in the database, we create this model.
b. The AddBook() model stores the data of books that are added in the library.
c. IssueBook() model stores the information of the book that is issued and also the studentid of the student to whom the book is issued.
d. ReturnBook() model contains the data of the book that is returned.
e. AddStudent() model stores the details of the student in the institution.
f. Foreign key: It is used to establish relationships with another table.
g. CharField(): It stores strings in the database.

4. Admin.py

from django.contrib import admin
from .models import AddBook,IssueBook,ReturnBook,AddStudent
 
# Register your models here for Python Library Management System.
from django.contrib.sessions.models import Session
admin.site.register(Session)
from .models import UserExtend
admin.site.register(UserExtend)
class AddBook_Admin(admin.ModelAdmin):
    list_display=("user","bookid","bookname","subject","category")
admin.site.register(AddBook,AddBook_Admin)
class IssueBookAdmin(admin.ModelAdmin):
    list_display=("user","book1","studentid")
admin.site.register(IssueBook,IssueBookAdmin)
class ReturnBookAdmin(admin.ModelAdmin):
    list_display=("user","bookid2")
admin.site.register(ReturnBook,ReturnBookAdmin)
class AddStudentAdmin(admin.ModelAdmin):
    list_display=("user","sname","studentid")
admin.site.register(AddStudent,AddStudentAdmin)

Code Explanation:

The models that are created in the models.py file are registered in admin.py. By adding models in admin.py these tables can be seen in the database.

a. register(): It helps to register the model in the database.

To see the tables you need to run migrations. Write the following command on your terminal window.

python manage.py makemigartions
python manage.py migrate

To access the database you need to create a superuser. To create a superuser, run the command given below on the terminal. It will prompt you to enter the username, password and email. After entering these fields superuser will be created.

python manage.py createsuperuser

5. Urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('',views.index,name='index'),
    path('staff/',views.staff,name='staff'),
    path('stafflogin/',views.stafflogin,name='stafflogin'),
    path('staffsignup/',views.staffsignup,name='staffsignup'),
    path('dashboard/',views.dashboard,name='dashboard'),
    path('addbook/',views.addbook,name='addbook'),
    path('SignupBackend/',views.SignupBackend,name='SignupBackend'),
    path('LoginBackend/',views.LoginBackend,name='LoginBackend'),
    path('AddBookSubmission/',views.AddBookSubmission,name='AddBookSubmission'),
    path('deletebook/<int:id>',views.deletebook,name='deletebook'),
    path('bookissue/',views.bookissue,name='bookissue'),
    path('returnbook/',views.returnbook,name='returnbook'),
    path('HandleLogout/',views.HandleLogout,name='HandleLogout'),
    path('issuebooksubmission/',views.issuebooksubmission,name='issuebooksubmission'),
    path('returnbooksubmission/',views.returnbooksubmission,name='returnbooksubmission'),
    path('Search/',views.Search,name='Search'),
    path('Searchstudent/',views.Searchstudent,name='Searchstudent'),
    path('editbookdetails/<int:id>',views.editbookdetails,name='editbookdetails'),
    path('<int:id>/updatedetails/',views.updatedetails,name='updatedetails'),
    path('addstudent/',views.addstudent,name='addstudent'),
    path('addstudentsubmission/',views.addstudentsubmission,name='addstudentsubmission'),
    path('viewissuedbook/',views.viewissuedbook,name='viewissuedbook'),
    path('viewstudents/',views.viewstudents,name='viewstudents')
]
 

Code Explanation:

If a person tries to access urls other than these he/she will not be able to access those urls. Create a urls.py file in the home folder.
a. path(): It returns the element that is included in the url patterns.

6. Views.py

a. Importing libraries:
from django.shortcuts import render,HttpResponse,redirect
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
from django.contrib import messages
from datetime import datetime,timedelta,date
from .models import IssueBook, UserExtend,AddBook,ReturnBook,AddStudent
from django.contrib.auth import authenticate ,logout
from django.contrib.auth import login as dj_login

Code Explanation:

a. Render: HttpResponse object is returned and it also combines the template with the dictionary that is passed in render.
b. HttpResponse:Text Response is displayed to the user with HttpResponse.
c. Redirect: It redirects the user to the desired page.
d. User: Authorization and authentication are handled with User.
e. messages: It helps in displaying messages to the user.
f. authenticate : A person can only log in if the user is a registered user. This work is done by authenticate.

b. Some functions that redirects a user to a particular page:
def index(request):
    return render(request,'index.html')
def staff(request):
    return render(request,'staff.html')
def stafflogin(request):
    if request.session.has_key('is_logged'):
        return redirect('dashboard')
    return render(request,'stafflogin.html')
def staffsignup(request):
    return render(request,'staffsignup.html')
def dashboard(request):
    if request.session.has_key('is_logged'):
        Book = AddBook.objects.all()
        return render(request,'dashboard.html',{'Book':Book})
    return redirect('stafflogin')

Code Explanation:

a. index() redirects to the home page.
b. staff() redirects to the staff page where a person gets the option to sign up and login.
c. stafflogin() redirects to the login page if a person is not logged in and if a person is logged in he/she will be redirected to the dashboard.
d. staffsignup() redirects to the signup page.
e. dashboard() redirects to the dashboard and displays all the books that are added.

c. Adding Books:
def addbook(request):
    Book = AddBook.objects.all()
    return render(request,'addbook.html',{'Book':Book})
def AddBookSubmission(request):
    if request.session.has_key('is_logged'):
        if request.method == "POST":
            user_id = request.session["user_id"]
            user1 = User.objects.get(id=user_id)
            bookid = request.POST["bookid"]
            bookname = request.POST["bookname"]
            subject = request.POST["subject"]
            category=request.POST["category"]
            add = AddBook(user = user1,bookid=bookid,bookname=bookname,subject=subject,category=category)
            add.save()
            Book = AddBook.objects.all()
            return render(request,'dashboard.html',{'Book':Book})
    return redirect('/')

Code Explanation:

a. addbook() redirects to the page where the book can be added.
b. AddBookSubmission() handles the backend of the adding book page. It stores bookid, book name, subject and category entered by the user in the database.

d. Login, Signup:
def SignupBackend(request):
    if request.method =='POST':
            uname = request.POST["uname"]
            fname=request.POST["fname"]
            lname=request.POST["lname"]
            email = request.POST["email"]
            phone=request.POST['phone']
            password=request.POST['password']
            userprofile = UserExtend(phone=phone)
            if request.method == 'POST':
                try:
                    UserExists = User.objects.get(username=request.POST['uname'])
                    messages.error(request," Username already taken, Try something else!!!")
                    return redirect("staffsignup")    
                except User.DoesNotExist:
                    if len(uname)>10:
                        messages.error(request," Username must be max 15 characters, Please try again")
                        return redirect("staffsignup")
            
                    if not uname.isalnum():
                        messages.error(request," Username should only contain letters and numbers, Please try again")
                        return redirect("staffsignup")
            
            # create the user
            user = User.objects.create_user(uname, email, password)
            user.first_name=fname
            user.last_name=lname
            user.email = email
            user.save()
            userprofile.user = user
            userprofile.save()
            messages.success(request," Your account has been successfully created")
            return redirect("stafflogin")
    else:
        return HttpResponse('404 - NOT FOUND ')
def LoginBackend(request):
    if request.method =='POST':
        loginuname = request.POST["loginuname"]
        loginpassword=request.POST["loginpassword"]
        RegisteredUser = authenticate(username=loginuname, password=loginpassword)
        if RegisteredUser is not None:
            dj_login(request, RegisteredUser)
            request.session['is_logged'] = True
            RegisteredUser = request.user.id 
            request.session["user_id"] = RegisteredUser
            messages.success(request, " Successfully logged in")
            return redirect('dashboard')
        else:
            messages.error(request," Invalid Credentials, Please try again")  
            return redirect("/")  
    return HttpResponse('404-not found')

Code Explanation:

a. SignupBackend() handles the backend of signup form.
b. LoginBackend() handles the backend of login form. To sign up a person needs to enter the username, first name , last name , email , phone number and password.
c. LoginBackend() checks whether a person is a registered user or not. If the person is registered he/she will be directed to the dashboard.

e. Deleting a book:
def deletebook(request,id):
    if request.session.has_key('is_logged'):
        AddBook_info = AddBook.objects.get(id=id)
        AddBook_info.delete()
        return redirect("dashboard")
    return redirect("login") 

Code Explanation:

a. deletebook() deletes the details of the book that is added. If a user is logged in, the selected row will be deleted with the help of delete() and after deleting the user will be redirected to the dashboard.

f. Issue Book:
def bookissue(request):
    return render(request,'bookissue.html')
def issuebooksubmission(request):
       if request.method=='POST':
            user_id = request.session["user_id"]
            user1 = User.objects.get(id=user_id)
            studentid=request.POST['studentid']
            book1=request.POST['book1']
            store=AddBook.objects.filter(bookid=book1)
            def get_category(addbook):
                if addbook.category=="Not-Issued":
                    addbook.category="Issued"
                    obj= IssueBook(user=user1,studentid=studentid,book1=book1)
                    obj.save()
                    addbook.save()
                else:
                    messages.error(request," Book already issued !!!")
            category_list=list(set(map(get_category,store)))         
            Issue=IssueBook.objects.all()
            return render(request,'bookissue.html',{'Issue':Issue})
       return redirect('/')

Code Explanation:

a. bookissue() redirects the user to the page where the book can be issued by entering the details of bookid and studentid.

b. issuebooksubmission() handles the backend of the form. It takes the information of bookid and studentid and stores it in the database and also it changes the status of the book from Not-Issued to Issued in the database as well as in the table that is displayed on the dashboard.

g. View Issued Books:
def viewissuedbook(request):
if request.session.has_key('is_logged'):
       issuedbooks=IssueBook.objects.all()
       lis=[]
       li=[]
       for books in issuedbooks:
           issdate=str(books.issuedate.day)+'-'+str(books.issuedate.month)+'-'+str(books.issuedate.year)
           expdate=str(books.expirydate.day)+'-'+str(books.expirydate.month)+'-'+str(books.expirydate.year)
           print(issdate)
           print(expdate)
           #fine calculation
           days=(date.today()-books.issuedate)
           d=days.days
           fine=0
           if d>15:
               day=d-15
               fine=day*10
           print(d)

           book=list(AddBook.objects.filter(bookid=books.book1))
           students=list(AddStudent.objects.filter(studentid=books.studentid))

           i=0
           for k in book:
               print(li)
               t=(students[i].sname,students[i].studentid,book[i].bookname,book[i].subject,issdate,expdate,fine)
               print(t)
               i=i+1
               lis.append(t)
               print(lis)

       return render(request,'viewissuedbook.html',{'lis':lis})
   return redirect('/')

Code Explanation:

a. viewissuedbook() function displays the table of books issued by the user and also the issue date, return date of a book and the fine. If the book is returned that row will automatically get deleted.

h. Returning a book:
def returnbook(request):
    return render(request,'returnbook.html')
def returnbooksubmission(request):
    if request.method=='POST':
            user_id = request.session["user_id"]
            user1 = User.objects.get(id=user_id)
            bookid2=request.POST['bookid2']
            store1=AddBook.objects.filter(bookid=bookid2)
            def return_book(returnbook):
                if returnbook.category=="Issued":
                    returnbook.category="Not-Issued"
                    obj1=ReturnBook(user=user1,bookid2=bookid2)
                    obj=IssueBook.objects.filter(book1=bookid2)
                    obj.delete()
                    obj1.save()
                    returnbook.save()
                else:
                    messages.error(request," Book not  issued !!!")
            returncategorylist=list(set(map(return_book,store1)))
            Return= ReturnBook.objects.all()
            return render(request,'returnbook.html',{'Return':Return})
    return redirect('/')

Code Explanation:

a. First function redirects the user to the page where the book can be returned by entering the bookid.

b. Second function handles the backend of the return book page. It stores the bookid of the book that is returned in the database and also it changes the status of the book to Not-Issued in the database as well as in the table displayed on the dashboard.

i. Logout of the profile:
def HandleLogout(request):
        del request.session['is_logged']
        del request.session["user_id"] 
        logout(request)
        messages.success(request, " Successfully logged out")
        return redirect('dashboard')

Code Explanation:

HandleLogout() function helps a user to log out from the library management system.

j. Search Bar:
j.Search Bar:
def Search(request):
    if request.session.has_key('is_logged'):
        query2=request.GET["query2"]
        Book=AddBook.objects.filter(bookid__icontains=query2)
        params={'Book':Book}
        return render(request,'dashboard.html',params)
    return redirect("login") 

Code Explanation:

Search() helps in searching the information related to books displayed on the dashboard. The user can get the details of the book by entering the bookid in the search bar.
a. filter(): Here, it filters only those rows of table that have the bookid similar to the one entered by the user.

k.Editing and Updating details of book:
def editbookdetails(request,id):
    if request.session.has_key('is_logged'):
        Book = AddBook.objects.get(id=id)
        return render(request,'editdetails.html',{'Book':Book})
    return redirect('login')
 
def updatedetails(request,id):
    if request.session.has_key('is_logged'):
        if request.method=="POST":
                add=AddBook.objects.get(id=id)
                add.bookid=request.POST["bookid"]
                add.bookname=request.POST["bookname"]
                add.subject=request.POST["subject"]
                add.ContactNumber=request.POST['category']
                add.save()
                return redirect("dashboard")
    return redirect('login')

Code Explanation:

a. The first function gets the details of the book which is to be edited and opens the edit form.
b. The second function stores the new details of the user in the database and updates the details in the table displayed on the dashboard.

l. Add Student:
    def addstudent(request):
if request.session.has_key('is_logged'):
       return render(request,'addstudent.html')
    return redirect ('login')
 
def viewstudents(request):
    if request.session.has_key('is_logged'):
        Student=AddStudent.objects.all()
        return render(request,'viewstudents.html',{'Student':Student})
    return redirect('stafflogin')
 
def Searchstudent(request):
    if request.session.has_key('is_logged'):
        query3=request.GET["query3"]
        Student=AddStudent.objects.filter(studentid__icontains=query3)
        params={'Student':Student}
        return render(request,'viewstudents.html',params)
    return redirect("stafflogin") 
 
def addstudentsubmission(request):
    if request.session.has_key('is_logged'):
        if request.method == "POST":
            user_id = request.session["user_id"]
            user1 = User.objects.get(id=user_id)
            sname = request.POST["sname"]
            studentid = request.POST["studentid"]
            add = AddStudent(user = user1,sname=sname,studentid=studentid)
            add.save()
            Student = AddStudent.objects.all()
            return render(request,'addstudent.html',{'Student':Student})
    return redirect('/')

Code Explanation:

a. addstudent() function helps to add the details of the student that are in the college or school.
b. viewstudents() helps to see all the students that are registered in the library.
c. searchstudent() helps to search the students that are registered.
d. addstudentsubmission() handles the backend of the addstudent form. It stores all the information of this form to the database.

Python Library Management System Output

a. Library Home:

library home

b. Staff Page:

staff page

c. Sign Up page:

library management system sign up

e. Dashboard:

library dashboard

g. Issue Book:

issue book

k. Book Search:

book search

Summary

We have successfully developed a library management system project in python. While developing the project we learned various concepts. It’s the perfect project for beginners.