Library Management System Project In Django With Source Code

Library Management System Project In Django With Source Code

A Library Management System In Django runs Django Framework in back-end and HTML, CSS in front-end. The project contains all the features of a library management like login, interactive UI, issue books, Manage books, Add books to the library.

This Django Library Management System also includes a downloadable Library Management System Project In Django Source Code for free, just find the downloadable source code below and click to start downloading.

To start creating a Library Management System Project In Django, makes sure that you have PyCharm Professional IDE Installed in your computer.

About ProjectProject DetailsDefinition
Project Name Library Management System Project In DjangoThe Library Management System Project In Django is developed using Python Django, HTML,CSS and JavaScript, The Library Management System Using Django is an advanced management system which provides interface.
Python version (Recommended)3.8 VersionPython 3.8 introduces some new syntax to the language, as well as a few small modifications to existing behavior and, most importantly, a slew of performance improvements, following in the footsteps of the previous 3.7 version.
Programming Language UsedPython Django LanguageDjango is a high-level Python web framework for building safe and maintainable websites quickly. Django is a web framework built by experienced developers that takes care of a lot of the heavy lifting so you can focus on developing your app instead of reinventing the wheel.
Developer Name itsourcecode.comFree projects containing source code in Java, PHP, Python, Django, VB.Net, Visual Basic, C, C++, C#, Javascript, and other languages are available on this website.
IDE Tool (Recommended)Sublime, Visual Studio, PyCharmSublime Text is a source code editor that is available for purchase. It comes with built-in support for a variety of programming and markup languages. Plugins, which are often community-built and maintained under free-software licenses, allow users to extend the functionality of the system. Sublime Text has a Python API to help with plugins.
Project Type Web ApplicationA web application, unlike computer-based software programs that operate locally on the device’s operating system, is application software that runs on a web server. The user uses a web browser with an active network connection to access web apps.
DatabaseSQLiteSQLite is a programming language that is used to create embedded software for devices such as televisions, cell phones, and cameras. It can handle HTTP requests with low to medium traffic. SQLite has the ability to compress files into smaller bundles with less metadata. SQLite is a temporary dataset that is used within an application to process data.
Library Management System Project In Django Overview

Reminders

Library Management System Project I...
Library Management System Project In Python and MySQL with Source Code 2021

To perform this python django project make sure that you have knowledge in the following:

  • CSS
  • HTML
  • Javascript
  • Database Management

Features Of This Library Management System Project In Django

  • Manage Books – In this feature the user can manage all the information of the books including, “add new book” , “update or modify book” and “delete book“.
  • Manage Users – In this feature the admin can manage all the information of users including, “add new user” , “update or modify user” and “delete user“.
  • Manage Students – In this feature the user can manage the list of the students.
  • Login/Logout System – In this feature where the user can login and logout to the system.

In This Library Management System Project In Django Consist Of The Following Method:

  1. library management – This method is the main method of the system project.
  2. management – In this method which is the management of the library system..
  3. media – This method you can found the uploading media like “photos” or other media file.
  4. template – This method id for the template design of the system including, “HTML“, “CSS” and etc.

Steps on how to create a Library Management System Project In Django With Source Code

Library Management System Project In Django With Source Code

  • Step 1: Open file.

    First , open “pycharm professional” after that click “file” and click “new project“.
    library management system open file

  • Step 2: Choose Django.

    Second, after click “new project“, choose “Django” and click.
    library management system create django

  • Step 3: Select file location.

    Third, select a file location wherever you want.
    library management system location

  • Step 4: Create application name.

    Fourth, name your application.
    library management system application name

  • Step 5: Click create.

    Fifth, finish creating project by clicking “create” button.
    library management system create project

  • Step 6: Start of coding.

    you are free to copy the following codes below in the given modules and method required.

The List Of Module Given Below Are Under The “library management” Method

  • The Code Given Below Is For The “settings.py” Module – you can add the following code below into your “setting.py” under the “library management” method.
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!!n61=9-q!_u=-0kcyu^[email protected][email protected]$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'management',
    'crispy_forms',

]
CRISPY_TEMPLATE_PACK = 'bootstrap4'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'management.middleware.GoogleSearch'

]

ROOT_URLCONF = 'Library_management.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Library_management.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails")
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

LOGIN_REDIRECT_URL = '/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In this module which is the module for setting up the installed apps, database and etc.

  • The Code Given Below Is For The “urls.py” Module – you can add the following code below into your “urls.py” under the “library_management” method.
from django.conf.urls import include,url
from django.contrib import admin
from django.urls import path


from django.conf import settings
from django.conf.urls.static import static

from management import views
from .feed import LatestEntriesFeed

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),

    path('books/', views.BookListView, name='books'),
    path('book/<int:pk>', views.BookDetailView, name='book-detail'),
    path('book/create/', views.BookCreate, name='book_create'),
    path('book/<int:pk>/update/', views.BookUpdate, name='book_update'),
    path('book/<int:pk>/delete/', views.BookDelete, name='book_delete'),

    path('student/<int:pk>/delete/', views.StudentDelete, name='student_delete'),
    path('student/create/', views.StudentCreate, name='student_create'),
    path('student<int:pk>/update/', views.StudentUpdate, name='student_update'),
    path('student/<int:pk>', views.StudentDetail, name='student_detail'),
    path('student/', views.StudentList, name='student_list'),
    path('student/book_list', views.student_BookListView, name='book_student'),
    path('book/<int:pk>/request_issue/', views.student_request_issue, name='request_issue'),

    path('feed/', LatestEntriesFeed(), name='feed'),
    path('return/<int:pk>', views.ret, name='ret'),
    path('rating/<int:pk>/update/', views.RatingUpdate, name='rating_update'),
    path('rating/<int:pk>/delete/', views.RatingDelete, name='rating_delete'),


url(r'^search_b/', views.search_book, name="search_b"),
url(r'^search_s/', views.search_student, name="search_s")
]
urlpatterns += [
    path('accounts/', include('django.contrib.auth.urls')),

]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In this module which is the URL configuration module under library management method.

The List Of Module Given Below Are Under The “management” Method

  • The Code Given Below Is For The “views.py” Module – you can add the following code below into your “views.py” under the “management” method.
from django.shortcuts import render, redirect

from .models import *
from .forms import *
# .FORMS REFERS TO THE FORMS.PY IN CURRENT DIRECTORY AND * USED FOR IMPORTING EVERYTHING

from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
import datetime

# HOME PAGE
def index(request):
    return render(
        request,
        'index.html',
    )


# VIEW THAT WILL RETURN LIST OF ALL BOOKS IN LIBRARY
def BookListView(request):
    book_list = Book.objects.all()
    # MODELNAME.objects.all() is used to get all objects i.e. tuples from database
    return render(request, 'catalog/book_list.html', locals())

@login_required
def student_BookListView(request):
    student=Student.objects.get(roll_no=request.user)
    bor=Borrower.objects.filter(student=student)
    book_list=[]
    for b in bor:
        book_list.append(b.book)
    # MODELNAME.objects.all() is used to get all objects i.e. tuples from database
    return render(request, 'catalog/book_list.html', locals())

#This view return detail of a particular book
#it also accepts a parameter pk that is the id  i.e. primary_key of book to identify it
#get_object_404 if object is not found then return 404 server error
#locals return a dictionary of loacl varibles
def BookDetailView(request, pk):
    book = get_object_or_404(Book, id=pk)
    reviews=Reviews.objects.filter(book=book).exclude(review="none")
    try:
        stu = Student.objects.get(roll_no=request.user)
        rr=Reviews.objects.get(review="none")
    except:
        pass
    return render(request, 'catalog/book_detail.html', locals())



@login_required
def BookCreate(request):
    if not request.user.is_superuser:
        return redirect('index')
    form = BookForm()
    if request.method == 'POST':
        form = BookForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            return redirect(index)
    return render(request, 'catalog/form.html', locals())


@login_required
def BookUpdate(request, pk):
    if not request.user.is_superuser:
        return redirect('index')
    obj = Book.objects.get(id=pk)
    form = BookForm(instance=obj)
    if request.method == 'POST':
        form = BookForm(data=request.POST, files=request.FILES, instance=obj)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.save()
            return redirect(index)
    return render(request, 'catalog/form.html', locals())


@login_required
def BookDelete(request, pk):
    if not request.user.is_superuser:
        return redirect('index')
    obj = get_object_or_404(Book, pk=pk)
    obj.delete()
    return redirect('index')



@login_required
def student_request_issue(request, pk):
    obj = Book.objects.get(id=pk)
    stu=Student.objects.get(roll_no=request.user)
    s = get_object_or_404(Student, roll_no=str(request.user))
    if s.total_books_due < 10:
        message = "book has been isuued, You can collect book from library"
        a = Borrower()
        a.student = s
        a.book = obj
        a.issue_date = datetime.datetime.now()
        obj.available_copies = obj.available_copies - 1
        obj.save()
        stu.total_books_due=stu.total_books_due+1
        stu.save()
        a.save()
    else:
        message = "you have exceeded limit."
    return render(request, 'catalog/result.html', locals())


@login_required
def StudentCreate(request):
    if not request.user.is_superuser:
        return redirect('index')
    form = StudentForm()
    if request.method == 'POST':
        form = StudentForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            s=form.cleaned_data['roll_no']
            form.save()
            u=User.objects.get(username=s)
            s=Student.objects.get(roll_no=s)
            u.email=s.email
            u.save()
            return redirect(index)
    return render(request, 'catalog/form.html', locals())


@login_required
def StudentUpdate(request, pk):
    if not request.user.is_superuser:
        return redirect('index')
    obj = Student.objects.get(id=pk)
    form = StudentForm(instance=obj)
    if request.method == 'POST':
        form = StudentForm(data=request.POST, files=request.FILES, instance=obj)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.save()
            return redirect(index)
    return render(request, 'catalog/form.html', locals())


@login_required
def StudentDelete(request, pk):
    obj = get_object_or_404(Student, pk=pk)
    obj.delete()
    return redirect('index')

@login_required
def StudentList(request):
    students = Student.objects.all()
    return render(request, 'catalog/student_list.html', locals())

@login_required
def StudentDetail(request, pk):
    student = get_object_or_404(Student, id=pk)
    books=Borrower.objects.filter(student=student)
    return render(request, 'catalog/student_detail.html', locals())




@login_required
def ret(request, pk):
    if not request.user.is_superuser:
        return redirect('index')
    obj = Borrower.objects.get(id=pk)
    book_pk=obj.book.id
    student_pk=obj.student.id
    student = Student.objects.get(id=student_pk)
    student.total_books_due=student.total_books_due-1
    student.save()

    book=Book.objects.get(id=book_pk)
    rating = Reviews(review="none", book=book,student=student,rating='2.5')
    rating.save()
    book.available_copies=book.available_copies+1
    book.save()
    obj.delete()
    return redirect('index')


import re

from django.db.models import Q

def normalize_query(query_string,
                    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                    normspace=re.compile(r'\s{2,}').sub):
    ''' Splits the query string in invidual keywords, getting rid of unecessary spaces
        and grouping quoted words together.
        Example:

        >>> normalize_query('  some random  words "with   quotes  " and   spaces')
        ['some', 'random', 'words', 'with quotes', 'and', 'spaces']

    '''
    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]

def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination
        aims to search keywords within a model by testing the given search fields.

    '''
    query = None # Query to search for every search term
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query
def search_book(request):
    query_string = ''
    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']

        entry_query = get_query(query_string, ['title', 'summary','author'])

        book_list= Book.objects.filter(entry_query)

    return render(request,'catalog/book_list.html',locals() )
def search_student(request):
    query_string = ''
    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']

        entry_query = get_query(query_string, ['roll_no','name','email'])

        students= Student.objects.filter(entry_query)

    return render(request,'catalog/student_list.html',locals())




@login_required
def RatingUpdate(request, pk):
    obj =Reviews.objects.get(id=pk)
    form = RatingForm(instance=obj)
    if request.method == 'POST':
        form = RatingForm(data=request.POST, instance=obj)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.save()
            return redirect('book-detail',pk=obj.book.id)
    return render(request, 'catalog/form.html', locals())


@login_required
def RatingDelete(request, pk):
    obj = get_object_or_404(Reviews, pk=pk)
    st=Student.objects.get(roll_no=request.user)
    if not st==obj.student:
        return redirect('index')
    pk = obj.book.id
    obj.delete()
    return redirect('book_detail',pk)

In this module which is the index module of the management method.

  • The Code Given Below Is For The “models.py” Module – you can add the following code below into your “models.py” under the “management” method.
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse  # Used to generate urls by reversing the URL patterns
from django.db.models.signals import post_save
#relation containg all genre of books
class Genre(models.Model):
    name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)")

    def __str__(self):
        return self.name
##  __str__ method is used to override default string returnd by an object


##relation containing language of books
class Language(models.Model):
    name = models.CharField(max_length=200,
                            help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)")

    def __str__(self):
        return self.name

#book relation that has 2 foreign key author language
#book relation can contain multiple genre so we have used manytomanyfield
class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
    isbn = models.CharField('ISBN', max_length=13,
                            help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
    genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
    language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
    total_copies = models.IntegerField()
    available_copies = models.IntegerField()
    pic=models.ImageField(blank=True, null=True, upload_to='book_image')

#return canonical url for an object
    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])

    ##  __str__ method is used to override default string returnd by an object
    def __str__(self):
        return self.title


def create_user(sender, *args, **kwargs):
    if kwargs['created']:
        user = User.objects.create(username=kwargs['instance'],password="dummypass")





#relation containing info about students
#roll_no is used for identifing students uniquely
class Student(models.Model):
    roll_no = models.CharField(max_length=10,unique=True)
    name = models.CharField(max_length=10)
    branch = models.CharField(max_length=3)
    contact_no = models.CharField(max_length=10)
    total_books_due=models.IntegerField(default=0)
    email=models.EmailField(unique=True)
    pic=models.ImageField(blank=True, upload_to='profile_image')
    def __str__(self):
        return str(self.roll_no)


post_save.connect(create_user, sender=Student)
#relation containing info about Borrowed books
#it has  foriegn key book and student for refrencing book nad student
#roll_no is used for identifing students
#if a book is returned than corresponding tuple is deleted from database
class Borrower(models.Model):
    student = models.ForeignKey('Student', on_delete=models.CASCADE)
    book = models.ForeignKey('Book', on_delete=models.CASCADE)
    issue_date = models.DateTimeField(null=True,blank=True)
    return_date = models.DateTimeField(null=True,blank=True)
    def __str__(self):
        return self.student.name+" borrowed "+self.book.title




class Reviews(models.Model):
    review=models.CharField(max_length=100,default="none")
    book=models.ForeignKey('Book',on_delete=models.CASCADE)
    student = models.ForeignKey('Student', on_delete=models.CASCADE)
    CHOICES = (
        ('0', '0'),
        ('.5', '.5'),
        ('1', '1'),
        ('1.5', '1.5'),
        ('2', '2'),
        ('2.5', '2.5'),
        ('3', '3'),
        ('3.5', '3.5'),
        ('4', '4'),
        ('4.5', '4.5'),
        ('5', '5'),
    )

    rating=models.CharField(max_length=3, choices=CHOICES, default='2')

In this module which you can found classes to be call under management method.

  • The Code Given Below Is For The “forms.py” Module – you can add the following code below into your “forms.py” under the “management” method.
from django import forms

from .models import *


class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'


class BorrowForm(forms.ModelForm):
    class Meta:
        model = Borrower
        exclude = ['issue_date', 'return_date']


class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
class RatingForm(forms.ModelForm):
    class Meta:
        model = Reviews
        exclude=['student','book']

In this module which is the students form under management method.

I have here the list of Best Python Project with Source code free to download for free, I hope this can help you a lot.

Downloadable Source Code Below.

Anyway, if you want to level up your programming knowledge, especially python, try this new article I’ve made for you Best Python Projects with source code for Beginners. But If you’re going to focus on web development using Django, you can download here from our list of Best Django Projects with source code based on real-world projects.

How To Run The Library Management System Project In Django?

Step 1: Extract/unzip the file

Step 2: Go inside the project folder, open cmd and type the following commands to install Django Framework and run the webserver:

1.) python manage.py runserver

Step 3: Finally, open the browser and go to localhost:8000

Summary

The system is built fully in Django Framework in back-end and HTML, CSS in front-end. It has full-featured user interface with all the functionalities

This Article is the way to enhance and develop our skills and logic ideas which is important in practicing the python programming language which is most well known and most usable programming language in many company.

Related article below

Inquiries

If you have any questions or suggestions about Library Management System Project In Django, please feel free to leave a comment below.

Leave a Comment