0% found this document useful (0 votes)
89 views

Lab Manual Python Programming 2021-2022-39-77

The document describes creating a Django web application for a library management system. It includes models for accounts, books, genres, languages, and borrowers. The application allows adding/deleting books, issuing/returning books to users, and searching by title or author. The goal is to develop a full-featured library management system using Django.

Uploaded by

rohithashwanth45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Lab Manual Python Programming 2021-2022-39-77

The document describes creating a Django web application for a library management system. It includes models for accounts, books, genres, languages, and borrowers. The application allows adding/deleting books, issuing/returning books to users, and searching by title or author. The goal is to develop a full-featured library management system using Django.

Uploaded by

rohithashwanth45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Task -11

TASK 11 a) Create a Django web application for simple calculator with basic
operations(+,-,*,%) with two numbers?

AIM: Develop a Django web application for simple calculator

38
Base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python LAB</title>
</head>
<body bgcolor="cyan">

{%block content %}
{% endblock %}
</body>
</html>

Home.html

{% extends 'base.html' %}

{% block content %}

<h1>Hello SRAVAN!!!</h1>

<form action="add" method="post">


{% csrf_token %}
Enter First Number: <input type="text" , name="num1"><br>
<label>Select operator</label>
<select name='opr' class="form-control">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>

39
</select><br>

Enter Second Number: <input type="text" , name="num2"><br>


<input type="submit">
</form>

{% endblock %}
Result.html
{% extends 'base.html' %}

{% block content %}

Result : {{res}}

{% endblock %}

Manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Example1.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "

40
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

if __name__ == '__main__':
main()

41
Output:

42
43
TASK 11 b) create a Django web application that implements Library MIS, which has
the features like,

i) Add/Delete a book
ii) Issue a book to a person
iii) Collect a book from a person
iv) Search for a title or author

AIM: Develop a Django web application that implements Library MIS

44
# Generated by Django 3.2.5 on 2022-01-13 00:55

import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid

class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]

operations = [
migrations.CreateModel(
name='Account',
fields=[
('password', models.CharField(max_length=128,
verbose_name='password')),
('id', models.UUIDField(default=uuid.uuid4, editable=False,
primary_key=True, serialize=False, unique=True)),
('email', models.EmailField(max_length=60, unique=True,
verbose_name='email')),
('name', models.CharField(max_length=60)),
('username', models.CharField(max_length=30, unique=True)),
('enrollment_no', models.IntegerField(default=52795,
unique=True)),
('date_joined', models.DateTimeField(auto_now_add=True,
verbose_name='date joined')),
('last_login', models.DateTimeField(auto_now=True,
verbose_name='last login')),
('pic', models.ImageField(blank=True, upload_to='students')),
('is_admin', models.BooleanField(default=False)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('is_superuser', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The
groups this user belongs to. A user will get all permissions granted to each of
their groups.', related_name='user_set', related_query_name='user',
to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True,
help_text='Specific permissions for this user.', related_name='user_set',
related_query_name='user', to='auth.Permission', verbose_name='user
permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False,
primary_key=True, serialize=False, unique=True)),

45
('title', models.CharField(max_length=200)),
('author', models.CharField(max_length=100)),
('summary', models.TextField(help_text='Enter a brief description
of the book', max_length=1000)),
('isbn', models.CharField(help_text='13 Character
https://www.isbn-international.org/content/what-isbn', max_length=13,
verbose_name='ISBN')),
('total_copies', models.IntegerField()),
('pic', models.ImageField(blank=True, null=True,
upload_to='books')),
('available_copies', models.IntegerField()),
],
),
migrations.CreateModel(
name='Genre',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter a book genre (e.g.
Science Fiction, French Poetry etc.)', max_length=200)),
],
),
migrations.CreateModel(
name='InformationForm',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=60, unique=True,
verbose_name='email')),
('name', models.CharField(max_length=60)),
('username', models.CharField(max_length=30, unique=True)),
('student', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='Language',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('name', models.CharField(help_text="Enter the book's natural
language (e.g. English, French, Japanese etc.)", max_length=200)),
],
),
migrations.CreateModel(
name='Borrower',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False,
primary_key=True, serialize=False, unique=True)),
('issue_date', models.DateField(blank=True,
default=datetime.date.today, help_text='YYYY-MM-DD', null=True)),
('return_date', models.DateField(blank=True, help_text='YYYY-MM-
DD', null=True)),
('book',
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='library.book')),
('student',
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL)),
],

46
),
migrations.AddField(
model_name='book',
name='genre',
field=models.ManyToManyField(help_text='Select a genre for this book',
to='library.Genre'),
),
migrations.AddField(
model_name='book',
name='language',
field=models.ForeignKey(null=True,
on_delete=django.db.models.deletion.SET_NULL, to='library.language'),
),
]

Base.html

<!doctype html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->


<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">

<title>Library Management System</title>


</head>
<style>

.card-img-top {
width: 100%;
height: 15vw;
object-fit: cover;
}
.card{
margin: 1em auto;
}
.about__img {
margin-top: 1em;
justify-self: center;
}
.profile{
margin: auto;
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', 'Calibri', 'Trebuchet MS', sans-
serif;

}
.about__img img {
width: 200px;
border-radius: .5rem;

47
}
label {
padding-top: 10px !important;
display: block;
}
th,td{
text-align: center;
margin: auto;
}
.flex-container{
overflow: auto;
}

</style>
<body class="container">

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<div class="container-fluid">
<a class="navbar-brand" href="{% url 'library:home' %}">Digital
Library</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav me-auto mb-2 mb-lg-0">


{% if request.user.is_authenticated %}
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url
'library:home' %}">Home</a>
</li>

{% if request.user.is_superuser or request.user.is_admin %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown"
role="button" data-bs-toggle="dropdown" aria-expanded="false">
Students
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="{% url 'library:student-list'
%}">Students List</a></li>
<li><a class="dropdown-item" href="{% url 'library:student-
create'%}">Add Student</a></li>

</ul>
</li>
{% endif %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown"
role="button" data-bs-toggle="dropdown" aria-expanded="false">
Books
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">

48
<li><a class="dropdown-item" href="{% url 'library:book-list'
%}">Books List</a></li>
{% if request.user.is_superuser or request.user.is_admin %}
<li><a class="dropdown-item" href="{% url 'library:book-create'
%}">Add New Book</a></li>
<li><a class="dropdown-item" href="{% url 'library:borrower-
create' %}">Issue a Book</a></li>
{% endif %}
<li><a class="dropdown-item" href="{% url 'library:borrower-list'
%}">Books Issued</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown"
role="button" data-bs-toggle="dropdown" aria-expanded="false">
Profile
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="{% url 'library:student-
detail' request.user.id%}">View Profile</a></li>
<li><a class="dropdown-item" href="{%url
'library:logout'%}">Logout</a></li>

</ul>
</li>
{% endif %}
</ul>
<form method="GET" class="d-flex">
<input class="form-control me-2" type="text" placeholder="Search"
name="search-area" aria-label="Search" value="{{search_input}}">
<button class="btn btn-outline-success"
type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="contaner" style="overflow: auto;">
{% block content %} {% endblock content %}</div>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>

</body>
</html>

49
Book_confirm_delete.html
{% extends 'library/base.html' %}
{% block content %}

<div >
<a href="{% url 'library:book-list' %}">&#8592;Back</a>
</div>

<div >
<form method = "POST">
{%csrf_token%}
<p>Are you sure you want to delete the book '{{book|title}}'?</p>
<input class="button" type="submit" value="Submit">
</form>
</div>

{% endblock content %}

All templates:

50
Admin.py

from django.contrib import admin


from .models import *
from django.contrib.auth.admin import UserAdmin

class AccountAdmin(UserAdmin):
list_display = ('email','name','username','date_joined', 'last_login',
'is_admin','is_staff')
search_fields = ('email','username',)
readonly_fields=('date_joined', 'last_login')
filter_horizontal = ()
list_filter = ()
fieldsets = ()

admin.site.register(Genre)
admin.site.register(Book)
admin.site.register(Language)
admin.site.register(Borrower)
admin.site.register(Account, AccountAdmin)
admin.site.register(InformationForm)

Forms.py

from django import forms


from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate

from .models import Account

class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Add a valid email
address.')

class Meta:
model = Account

51
fields = ('email', 'name', 'username','enrollment_no', 'password1',
'password2','pic' )

class AccountAuthenticationForm(forms.ModelForm):

password = forms.CharField(label='Password', widget=forms.PasswordInput)

class Meta:
model = Account
fields = ('email', 'password')

def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError("Invalid login")

class AccountUpdateForm(forms.ModelForm):

class Meta:
model = Account
fields = ('email','name' ,'username', 'pic' )

def clean_email(self):
email = self.cleaned_data['email']
try:
account =
Account.objects.exclude(pk=self.instance.pk).get(email=email)
except Account.DoesNotExist:
return email
raise forms.ValidationError('Email "%s" is already in use.' % account)

def clean_username(self):
username = self.cleaned_data['username']
try:
account =
Account.objects.exclude(pk=self.instance.pk).get(username=username)
except Account.DoesNotExist:
return username
raise forms.ValidationError('Username "%s" is already in use.' % username)

models.py

from django.db import models


from django.contrib.auth.models import User
# Used to generate urls by reversing the URL patterns
from django.urls import reverse
from django.db.models.signals import post_save
from django.contrib.auth.models import PermissionsMixin
from django.utils.timezone import now
import uuid
import random
# relation containg all genre of books

52
from datetime import date, timedelta, datetime
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class MyAccountManager(BaseUserManager):
def create_user(self, email, name, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')

user = self.model(
email=self.normalize_email(email),
username=username,
name=name,

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, name, username, password):


user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
name=name,

)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user

class Account(AbstractBaseUser, PermissionsMixin):


id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
name = models.CharField(max_length=60, unique=False)
username = models.CharField(max_length=30, unique=True)
enrollment_no = models.IntegerField(
unique=True, default=random.randint(10000, 99999))
date_joined = models.DateTimeField(
verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
pic = models.ImageField(blank=True, upload_to='students')
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)

USERNAME_FIELD = 'email'

53
REQUIRED_FIELDS = ['name', 'username']

objects = MyAccountManager()

def __str__(self):
return f'{self.name}'

# For checking permissions. to keep it simple all admin have ALL


permissons
def has_perm(self, perm, obj=None):
return self.is_admin

# Does this user have permission to view this app? (ALWAYS YES FOR
SIMPLICITY)
def has_module_perms(self, app_label):
return True

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 genre language


# book relation can contain multiple genre so we have used manytomanyfield

class Book(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
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 https://www.isbn-
international.org/content/what-isbn')
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()
pic = models.ImageField(blank=True, null=True, upload_to='books')
available_copies = models.IntegerField(name='available_copies')

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

# relation containing info about Borrowed books


# it has foriegn key book and student for refrencing book and student
# roll_no is used for identifing students
# if a book is returned than corresponding tuple is deleted from database
class Borrower(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
student = models.ForeignKey('Account', on_delete=models.CASCADE)
book = models.ForeignKey('Book', on_delete=models.CASCADE)
issue_date = models.DateField(
null=True, blank=True, help_text='YYYY-MM-DD', default=date.today)
return_date = models.DateField(
null=True, blank=True, help_text='YYYY-MM-DD')

def __str__(self):
return self.student.name.title()+" borrowed "+self.book.title.title()

def fine(self):
today = date.today()
fine = 0
if self.return_date <= today:
fine += 5 * (today - self.return_date).days
return fine

class InformationForm(models.Model):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
name = models.CharField(max_length=60, unique=False)
username = models.CharField(max_length=30, unique=True)
student = models.BooleanField(default=False)

def __str__(self):
return self.email

55
test.py

Urls.py

56
from django.shortcuts import render, redirect, get_object_or_404
from .models import *
from django.views.generic import TemplateView
from django.views.generic.edit import CreateView, DeleteView, UpdateView, FormView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.contrib.auth.views import LoginView
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.urls import reverse_lazy
from .forms import *
from django.http import request
from datetime import datetime, timedelta
from django.contrib import messages

class UserAccessMixin(PermissionRequiredMixin):
def dispatch(self, request, *args, **kwargs):
if not self.has_permission():
return redirect('library:home')
return super(UserAccessMixin, self).dispatch(request, *args, **kwargs)

class UserLoginView(LoginView):
template_name='library/login.html'
fields='__all__'
redirect_authenticated_user=True

def get_success_url(self):
return reverse_lazy('library:home')

class InformationView(CreateView):
template_name='library/information_form.html'
model=InformationForm
context_object_name="account_register"
fields=['email', 'name', 'username', 'student']
success_url=reverse_lazy('library:login')

def form_valid(self, form):


form.instance.user=self.request.user
return super(InformationView, self).form_valid(form)

class HomeView(LoginRequiredMixin, TemplateView):


template_name='library/main.html'

def get_context_data(self, **kwargs):


context=super().get_context_data(**kwargs)
context['accounts']=Account.objects.all()
context['books'] = Book.objects.all()
search_input=self.request.GET.get('search-area') or ''
if search_input:
context['books']=context['books'].filter(
title__startswith=search_input)

57
context['search_input']=search_input
return context

class BookView(LoginRequiredMixin, ListView):


model=Book
context_object_name='books'

def get_context_data(self, **kwargs):


context=super().get_context_data(**kwargs)
context['books']=context['books']

search_input=self.request.GET.get('search-area') or ''
if search_input:
context['books']=context['books'].filter(
title__startswith=search_input)

context['search_input']=search_input

return context

class BookCreate(LoginRequiredMixin, UserAccessMixin, CreateView):


model=Book
permission_required= 'books.add_books'
fields='__all__'
success_url=reverse_lazy('library:book-list')

def form_valid(self, form):


form.instance.user=self.request.user
return super(BookCreate, self).form_valid(form)

class BookDetail(LoginRequiredMixin, DetailView):


model=Book
context_object_name='book'
template_name='library/book.html'

class BookUpdate(LoginRequiredMixin,UserAccessMixin, UpdateView):


model=Book
permission_required = 'books.change_books'
fields='__all__'
success_url=reverse_lazy('library:book-list')

class BookDelete(LoginRequiredMixin,UserAccessMixin, DeleteView):


model=Book
permission_required = 'books.delete_book'
context_object_name='book'
fields='__all__'
success_url=reverse_lazy('library:book-list')

58
class StudentView(LoginRequiredMixin, UserAccessMixin, ListView):
model=Account
context_object_name='students'
permission_required = 'students.view_students'
template_name='library/student_list.html'

def get_context_data(self, *args,**kwargs):


context=super().get_context_data(**kwargs)
context['students']=context['students'].exclude(is_admin=True)
search_input=self.request.GET.get('search-area') or ''
if search_input:

context['students']=context['students'].filter(name__startswith=search_input)

context['search_input']=search_input

return context

class StudentDetail(LoginRequiredMixin, DetailView):


model=Account
context_object_name='student'
template_name='library/student.html'

class StudentCreate(UserAccessMixin, CreateView):


template_name = 'library/register.html'
form_class = RegistrationForm
permission_required = 'users.add_users'
success_url = reverse_lazy('library:student-list')

def form_valid(self, form):


form.instance.user=self.request.user
return super(StudentCreate, self).form_valid(form)

class StudentUpdate(LoginRequiredMixin, UpdateView):


form_class = AccountUpdateForm
template_name = 'library/student_update.html'
model = Account
success_url=reverse_lazy('library:student-list')

def form_valid(self, form):


user = form.save()
return super(StudentUpdate, self).form_valid(form)

class StudentDelete(LoginRequiredMixin,UserAccessMixin, DeleteView):


model=Account
template_name = 'library/student_confirm_delete.html'
permission_required = 'users.delete_users'
context_object_name='student'
fields='__all__'
success_url=reverse_lazy('library:student-list')

59
class BorrowerView(LoginRequiredMixin, ListView):
model=Borrower
context_object_name='borrowers'
template_name = 'library/borrower_list.html'

def get_context_data(self, **kwargs):


context=super().get_context_data(**kwargs)
if self.request.user.is_admin or self.request.user.is_superuser:
context['borrowers']=context['borrowers']
else:
context['borrowers']=context['borrowers'].filter(student =
self.request.user.id)

return context

class BorrowerCreate(LoginRequiredMixin, UserAccessMixin, CreateView):


model=Borrower
permission_required= 'borrowers.add_borrowers'
fields='__all__'
success_url=reverse_lazy('library:borrower-list')

#remember to get the object using slug or 404


def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
book = Book.objects.get(id=instance.book.id)
student = Account.objects.get(id=instance.student.id)
#get the book id from the form and check if the book is still available,
then subtract.
if book.available_copies > 0:
book.available_copies -= 1
book.save()
instance.save()
messages.success(self.request, "successful")
messages.error(self.request, "Book not in stock")
return redirect(reverse_lazy('library:borrower-list'))

class BorrowerDetail(LoginRequiredMixin, DetailView):


model=Borrower()
context_object_name='borrower'
template_name='library/borrower.html'

class BorrowerUpdate(LoginRequiredMixin,UserAccessMixin, UpdateView):


model=Borrower
permission_required = 'borrowers.change_borrowers'
fields='__all__'
success_url=reverse_lazy('library:borrower-list')

class BorrowerDelete(LoginRequiredMixin,UserAccessMixin, DeleteView):


model=Borrower

60
permission_required = 'borrowers.delete_borrowers'
context_object_name='borrower'
fields='__all__'
success_url=reverse_lazy('library:borrower-list')

def delete(self, request, *args, **kwargs):


self.object = self.get_object()
success_url = self.get_success_url()
book = Book.objects.get(id=self.object.book.id)
book.available_copies +=1
book.save()
self.object.delete()
return redirect('library:borrower-list')

outputs:

61
Search by title

62
Books issued

Admin login:

63
Add a new book:

64
Issuing a book to student:

65
TASK-12

TASK 12) Create a Django web application that implements a bus can be
added/removed with a given source and destination. A user should be able to reserve or
cancel a seat?

AIM: Django web application that implements a bus ticket reservation system.

Manage.py

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

urls.py

66
Admin.py

67
App.py

Forms.py

from django import forms


from django.contrib.auth import (
authenticate,
get_user_model

User = get_user_model()

class UserLoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)

def clean(self, *args, **kwargs):


username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')

if username and password:


user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError('This user does not exist')
if not user.check_password(password):
raise forms.ValidationError('Incorrect password')
if not user.is_active:
raise forms.ValidationError('This user is not active')
return super(UserLoginForm, self).clean(*args, **kwargs)

class UserRegisterForm(forms.ModelForm):
email = forms.EmailField(label='Email address')
email2 = forms.EmailField(label='Confirm Email')
password = forms.CharField(widget=forms.PasswordInput)

class Meta:
model = User
fields = [
'username',
'email',

68
'email2',
'password'
]

def clean(self, *args, **kwargs):


email = self.cleaned_data.get('email')
email2 = self.cleaned_data.get('email2')
if email != email2:
raise forms.ValidationError("Emails must match")
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError(
"This email has already been registered")
return super(UserRegisterForm, self).clean(*args, **kwargs)

models.py

# Create your models here.


from django.db import models

# Create your models here.

class Bus(models.Model):
bus_name = models.CharField(max_length=30)
source = models.CharField(max_length=30)
dest = models.CharField(max_length=30)
nos = models.DecimalField(decimal_places=0, max_digits=2)
rem = models.DecimalField(decimal_places=0, max_digits=2)
price = models.DecimalField(decimal_places=2, max_digits=6)
date = models.DateField()
time = models.TimeField()

def __str__(self):
return self.bus_name

class User(models.Model):
user_id = models.AutoField(primary_key=True)
email = models.EmailField()
name = models.CharField(max_length=30)
password = models.CharField(max_length=30)

def __str__(self):
return self.email

class Book(models.Model):
BOOKED = 'B'
CANCELLED = 'C'

TICKET_STATUSES = ((BOOKED, 'Booked'),


(CANCELLED, 'Cancelled'),)
email = models.EmailField()
name = models.CharField(max_length=30)
userid =models.DecimalField(decimal_places=0, max_digits=2)
busid=models.DecimalField(decimal_places=0, max_digits=2)
bus_name = models.CharField(max_length=30)

69
source = models.CharField(max_length=30)
dest = models.CharField(max_length=30)
nos = models.DecimalField(decimal_places=0, max_digits=2)
price = models.DecimalField(decimal_places=2, max_digits=6)
date = models.DateField()
time = models.TimeField()
status = models.CharField(choices=TICKET_STATUSES, default=BOOKED,
max_length=2)

def __str__(self):
return self.email

Views.py

from django.shortcuts import render


from decimal import Decimal

# Create your views here.


from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import User, Bus, Book
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from .forms import UserLoginForm, UserRegisterForm
from django.contrib.auth.decorators import login_required
from decimal import Decimal

def home(request):
if request.user.is_authenticated:
return render(request, 'myapp/home.html')

70
else:
return render(request, 'myapp/signin.html')

@login_required(login_url='signin')
def findbus(request):
context = {}
if request.method == 'POST':
source_r = request.POST.get('source')
dest_r = request.POST.get('destination')
date_r = request.POST.get('date')
bus_list = Bus.objects.filter(source=source_r, dest=dest_r, date=date_r)
if bus_list:
return render(request, 'myapp/list.html', locals())
else:
context["error"] = "Sorry no buses availiable"
return render(request, 'myapp/findbus.html', context)
else:
return render(request, 'myapp/findbus.html')

@login_required(login_url='signin')
def bookings(request):
context = {}
if request.method == 'POST':
id_r = request.POST.get('bus_id')
seats_r = int(request.POST.get('no_seats'))
bus = Bus.objects.get(id=id_r)
if bus:
if bus.rem > int(seats_r):
name_r = bus.bus_name
cost = int(seats_r) * bus.price
source_r = bus.source
dest_r = bus.dest
nos_r = Decimal(bus.nos)
price_r = bus.price
date_r = bus.date
time_r = bus.time
username_r = request.user.username
email_r = request.user.email
userid_r = request.user.id
rem_r = bus.rem - seats_r
Bus.objects.filter(id=id_r).update(rem=rem_r)
book = Book.objects.create(name=username_r, email=email_r,
userid=userid_r, bus_name=name_r,
source=source_r, busid=id_r,
dest=dest_r, price=price_r,
nos=seats_r, date=date_r, time=time_r,
status='BOOKED')
print('------------book id-----------', book.id)
# book.save()
return render(request, 'myapp/bookings.html', locals())
else:
context["error"] = "Sorry select fewer number of seats"
return render(request, 'myapp/findbus.html', context)

else:
return render(request, 'myapp/findbus.html')

71
@login_required(login_url='signin')
def cancellings(request):
context = {}
if request.method == 'POST':
id_r = request.POST.get('bus_id')
#seats_r = int(request.POST.get('no_seats'))

try:
book = Book.objects.get(id=id_r)
bus = Bus.objects.get(id=book.busid)
rem_r = bus.rem + book.nos
Bus.objects.filter(id=book.busid).update(rem=rem_r)
#nos_r = book.nos - seats_r
Book.objects.filter(id=id_r).update(status='CANCELLED')
Book.objects.filter(id=id_r).update(nos=0)
return redirect(seebookings)
except Book.DoesNotExist:
context["error"] = "Sorry You have not booked that bus"
return render(request, 'myapp/error.html', context)
else:
return render(request, 'myapp/findbus.html')

@login_required(login_url='signin')
def seebookings(request,new={}):
context = {}
id_r = request.user.id
book_list = Book.objects.filter(userid=id_r)
if book_list:
return render(request, 'myapp/booklist.html', locals())
else:
context["error"] = "Sorry no buses booked"
return render(request, 'myapp/findbus.html', context)

def signup(request):
context = {}
if request.method == 'POST':
name_r = request.POST.get('name')
email_r = request.POST.get('email')
password_r = request.POST.get('password')
user = User.objects.create_user(name_r, email_r, password_r, )
if user:
login(request, user)
return render(request, 'myapp/thank.html')
else:
context["error"] = "Provide valid credentials"
return render(request, 'myapp/signup.html', context)
else:
return render(request, 'myapp/signup.html', context)

def signin(request):
context = {}
if request.method == 'POST':
name_r = request.POST.get('name')
password_r = request.POST.get('password')
user = authenticate(request, username=name_r, password=password_r)
if user:

72
login(request, user)
# username = request.session['username']
context["user"] = name_r
context["id"] = request.user.id
return render(request, 'myapp/success.html', context)
# return HttpResponseRedirect('success')
else:
context["error"] = "Provide valid credentials"
return render(request, 'myapp/signin.html', context)
else:
context["error"] = "You are not logged in"
return render(request, 'myapp/signin.html', context)

def signout(request):
context = {}
logout(request)
context['error'] = "You have been logged out"
return render(request, 'myapp/signin.html', context)

def success(request):
context = {}
context['user'] = request.user
return render(request, 'myapp/success.html', context)

OUTPUT:

Admin Login:
Admin_ABC
First create a superuser/admin form cmd promt using following cmd:
>python manage.py createsuperuser

Adding a bus:

73
Bus can be deleted:

Search for a bus:

74
Book a bus:

75
Cancellation :

76

You might also like