Aman Seminar Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

A SEMINAR REPORT

ON

Python with Django


Submitted in partial fulfillment of the requirement for the award of Degree of
Bachelor of Technology in Computer Science & Engineering

Submitted to:

Rajasthan Technical University, Kota (Raj.)

Submitted By:
Aman Mishra (16EARCS022)

Under the supervision of

Er. Jaideep Manocha

Session: 2019-2020

Department of Computer Science & Engineering


ARYA COLLEGE OF ENGINEERING & I.T.,
SP-42, RIICO INDUSTRIAL AREA, KUKAS, JAIPUR

CERTIFICATE

This is to certify that Aman Mishra (16EARCS022) has successfully delivered Seminar to satisfaction and
report is submitted for partial fulfillment of requirement for the award of degree of Bachelor of Technology
in Computer Science & Engineering under Rajasthan Technical University, Kota.

Seminar Cordinator
Er. Jaideep Manocha

Dr. Akhil Pandey


Head of Department
Computer Science & Engineering
ACKNOWLEDGEMENT

I would like to thank sincerely to my guide Er. Jaideep Manocha for his invaluable guidance,
constant assistance, support and constructive suggestions for the betterment of the technical
seminar. I would like to convey my heartfelt thanks to our Head of Department Dr. Akhil
Pandey for giving me the opportunity to embark upon this topic and for his continued
encouragement throughout the preparation of this presentation. I also want to thank all the
staff members of the department of Computer Engineering for helping directly or indirectly in
completing this work successfully. Finally, I am thankful to my parents and friends for their
continued moral and material support throughout the course and in helping me finalize the
report.

Aman Mishra
final year 8th semester (16EARCS022)
Department of Computer Engineering
Arya College of Engineering & I.T., Jaipur
LIST OF CONTENTS
1. INTRODUCTION
1.1 What is Python …………………………………………………
1.2 Why is so Popular
1.3 In which field python is used
(A) Console based applications
(B)Web applications
2. Web Development
2.1 Introduction to web development with python………………………………..
2.2 Introduction to Django………………………………………………………...
2.3 Why Django is so popular…………………………………………………….

3. APPLICATION AND CASE STUDY


4. CONCLUSION
5. REFERENCE
ABSTRACT

The objective of this briefing is to present an overview of the python currently in use in web
applications , mobile applications , desktop applications. Section I, outlines the main reason
why python is so popular and why it is more useful. discuss current research or applications
of python within the field of official statistics in the areas of automatic coding, editing and
imputation, and record linkage, respectively. The material presented in this report is the result
of a literature review, of direct contacts with authors during conferences, and more
importantly of an international call for input that was distributed on July 18, 2014 to
participants from the 2014 MSIS Meeting, participants from the 2014 Work Session on
Statistical Data Editing, and members of the Modernization Committee on Production and
Methods.
INTRODUCTION TO TOPIC

What is python?

Python is an interpreted high level , general purpose programming language created by guido van rossum
and first released in 1991. Python's design philosphy emphasized code readability with notable used of
significance whitespace.
Python was conceived in the late 1980 as successor to abc language.

More about python

According to the latest TIOBE Programming Community Index, Python is one of the top 10 popular
programming languages of 2017. Python is a general purpose and high level programming language. You can
use Python for developing desktop GUI applications, websites and web applications. Also, Python, as a high
level programming language, allows you to focus on core functionality of the application by taking care of
common programming tasks.
Why is so popular

1) Readable and Maintainable Code


While writing a software application, you must focus on the quality of its source code to simplify maintenance
and updates. The syntax rules of Python allow you to express concepts without writing additional code. At the
same time, Python, unlike other programming languages, emphasizes on code readability, and allows you to
use English keywords instead of punctuations. Hence, you can use Python to build custom applications without
writing additional code. The readable and clean code base will help you to maintain and update the software
without putting extra time and effort.
2) Multiple Programming Paradigms
Like other modern programming languages, Python also supports several programming paradigm. It supports
object oriented and structured programming fully. Also, its language features support various concepts in
functional and aspect-oriented programming. At the same time, Python also features a dynamic type system and
automatic memory management. The programming paradigms and language features help you to use Python
for developing large and complex software applications.
3) Compatible with Major Platforms and Systems
At present, Python is supports many operating systems. You can even use Python interpreters to run the code
on specific platforms and tools. Also, Python is an interpreted programming language. It allows you to you to
run the same code on multiple platforms without recompilation. Hence, you are not required to recompile the
code after making any alteration. You can run the modified application code without recompiling and check the
impact of changes made to the code immediately. The feature makes it easier for you to make changes to the
code without increasing development time.
4) Robust Standard Library
Its large and robust standard library makes Python score over other programming languages. The standard
library allows you to choose from a wide range of modules according to your precise needs. Each module further
enables you to add functionality to the Python application without writing additional code. For instance, while
writing a web application in Python, you can use specific modules to implement web services, perform string
operations, manage operating system interface or work with internet protocols. You can even gather information
about various modules by browsing through the Python Standard Library documentation.
5) Many Open Source Frameworks and Tools
As an open source programming language, Python helps you to curtail software development cost significantly.
You can even use several open source Python frameworks, libraries and development tools to curtail
development time without increasing development cost. You even have option to choose from a wide range of
open source Python frameworks and development tools according to your precise needs. For instance, you can
simplify and speedup web application development by using robust Python web frameworks like Django, Flask,
Pyramid, Bottle and Cherrypy. Likewise, you can accelerate desktop GUI application development using
Python GUI frameworks and toolkits like PyQT, PyJs, PyGUI, Kivy, PyGTK and WxPython.
6) Simplify Complex Software Development
Python is a general purpose programming language. Hence, you can use the programming language for
developing both desktop and web applications. Also, you can use Python for developing complex scientific and
numeric applications. Python is designed with features to facilitate data analysis and visualization. You can take
advantage of the data analysis features of Python to create custom big data solutions without putting extra time
and effort. At the same time, the data visualization libraries and APIs provided by Python help you to visualize
and present data in a more appealing and effective way. Many Python developers even use Python to
accomplish artificial intelligence (AI) and natural language processing tasks.
7) Adopt Test Driven Development
You can use Python to create prototype of the software application rapidly. Also, you can build the software
application directly from the prototype simply by refactoring the Python code. Python even makes it easier for
you to perform coding and testing simultaneously by adopting test driven development (TDD) approach. You
can easily write the required tests before writing code and use the tests to assess the application code
continuously. The tests can also be used for checking if the application meets predefined requirements based on
its source code.
However, Python, like other programming languages, has its own shortcomings. It lacks some of the built-in
features provided by other modern programming language. Hence, you have to use Python libraries, modules,
and frameworks to accelerate custom software development. Also, several studies have shown that Python is
slower than several widely used programming languages including Java and C++. You have to speed up the
Python application by making changes to the application code or using custom runtime. But you can always use
Python to speed up software development and simplify software maintenance.

In which field python is used?

Consol applications
A console application is a computer program designed to be used via a text-only computer interface, such as a
text terminal, the command line interface of some operating systems (Unix, DOS, etc.) or the text-based
interface included with most Graphical User Interface (GUI) operating systems, such as the Win32 console in
Microsoft Windows, the Terminal in Mac OS X, and xterm in Unix. A user typically interacts with a console
application using only a keyboard and display screen, as opposed to GUI applications, which normally require
the use of a mouse or other pointing device. Many console applications such as command line interpreters are
command line tools, but numerous text-based user interface (TUI) programs also exist.
As the speed and ease-of-use of GUIs applications have improved over time, the use of console applications
has greatly diminished, but not disappeared. Some users simply prefer console based applications, while some
organizations still rely on existing console applications to handle key data processing tasks.
The ability to create console applications is kept as a feature of modern programming environments such as
Visual Studio and the .NET Framework on Microsoft Windows because it greatly simplifies the learning process
of a new programming language by removing the complexity of a graphical user interface (see an example in
the C# article).
For data processing tasks and computer administration, these programming environments represent the next
level of operating system or data processing control after scripting. If an application is only going to be run by
the original programmer and/or a few colleagues, there may be no need for a pretty graphical user interface,
leaving the application leaner, faster and easier to maintain.
Console-based applications include Alpine (an e-mail client), cmus (an audio player), Irssi (an IRC client), Lynx
(a web browser), Midnight Commander (a file manager), Music on Console (an audio player), Mutt (an e-mail
client), nano (a text editor), ne (a text editor), newsbeuter (an RSS reader), and ranger (a file manager).

GUI applications

python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods,
tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with
Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI
To create a tkinter:
6. Importing the module – tkinter
7. Create the main window (container)
8. Add any number of widgets to the main window
9. Apply the event Trigger on the widgets.
Importing tkinter is same as importing any other module in the python code. Note that the name of the module
in Python 2.x is ‘Tkinter’ and in Python 3.x is ‘tkinter’.

10. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window,


tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To
change the name of the window, you can change the className to the desired one. The basic code
used to create the main window of the application is:m=tkinter.Tk() where m is the name of
the main window object
11. mainloop(): There is a method known by the name mainloop() is used when you are ready for the
application to run. mainloop() is an infinite loop used to run the application, wait for an event to occur
and process the event till the window is not closed.m.mainloop()
12. filter_none
13. brightness_4
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the
parent windows. There are mainly three geometry manager classes class.
14. pack() method:It organizes the widgets in blocks before placing in the parent widget.
15. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent
widget.
16. place() method:It organizes the widgets by placing them on specific positions directed by the
programmer.
There are a number of widgets which you can put in your tkinter application. Some of the major widgets are
explained below:
17. Button:To add a button in your application, this widget is used.
The general syntax is:w=Button(master, option=value)
18. master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: to set the background color when button is under the cursor.
 activeforeground: to set the foreground color when button is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.

 filter_none
 edit
 play_arrow
 brightness_4
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
 Output:

19. Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:w = Canvas(master, option=value)master is the parameter used to
represent the parent window.
20. There are number of options which are used to change the format of the widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the widget.

 filter_none
 edit
 play_arrow
 brightness_4
from tkinter import *
master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
 Output:

21. CheckButton: To select any number of options by displaying a number of options to a user as toggle
buttons. The general syntax is:w = CheckButton(master, option=value)
22. There are number of options which are used to change the format of this widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
 Title: To set the title of the widget.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set he normal backgroudSteganography
 Break
 Secret Code:
 Attach a File:nd color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
 filter_none
 edit
 play_arrow
 Web applications

What is django:-
Django is a Python-based web framework which allows you to quickly create web application without all of the
installation or dependency problems that you normally will find with other frameworks.
When you’re building a website, you always need a similar set of components: a way to handle user
authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to
upload files, etc. Django gives you ready-made components to use.
Why Django?
23. It’s very easy to switch database in Django framework.
24. It has built-in admin interface which makes easy to work with it.
25. Django is fully functional framework that requires nothing else.
26. It has thousands of additional packages available.
27. It is very scalable.
Popularity of Django
Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation,
Mozilla, National Geographic etc. There are more than 5k online sites based on the Django framework. ( Source
)
Sites like Hot Frameworks assess the popularity of a framework by counting the number of GitHub projects
and StackOverflow questions for each platform, here Django is in 6th position. Web frameworks often refer to
themselves as “opinionated” or “un-opinionated” based on opinions about the right way to handle any particular
task. Django is somewhat opinionated, hence delivers the in both worlds( opinionated & un-opinionated ).
Some features of Django
Versatility of Django
Django can build almost any type of website. It can also work with any client-side framework and can deliver
content in any format such as HTML, JSON, XML etc. Some sites which can be built using Django are wikis,
social networks, new sites etc.

Security
Since Django framework is made for making web development easy, it has been engineered in such a way that
it automatically do the right things to protect the website. For example, In the Django framework instead of
putting a password in cookies, the hashed password is stored in it so that it can’t be fetched easily by hackers.
Scalability
Django web nodes have no stored state, they scale horizontally – just fire up more of then when you need them.
Being able to do this is the essence of good scalability. Instagram and Disqus are two Django based products
that have millions of active users, this is taken as an example of the scalability of Django.
Portability
All the codes of the Django framework are written in Python, which runs on many platforms. Which leads to
run Django too in many platforms such as Linux, Windows and Mac OS.
Installation of Django
 Install python3 if not installed in your system ( according to configuration of your system and OS)
from here . Try to download the latest version of python it’s python3.6.4 this time.
 Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for Linux
and mac just open terminal in place of command prompt and go through the following commands.
 Install pip- Open command prompt and enter following command-
 python -m pip install -U pip


 Install virtual environment- Enter following command in cmd-
 pip install virtualenv

 Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency
which generally your system wouldn’t allow.
Follow these steps to set up a virtual environment-
27.1 Create a virtual environment by giving this command in cmd-virtualenv env_site

27.2
27.3 Change directory to env_site by this command-cd env_site

27.4
27.5

27.6 Go to Script directory inside env_site and activate virtual environment-cd Scriptactivate

27.7
 Install Django- Install django by giving following command-pip install django

 Return to the env_site directory-cd ..


 Start a project by following command-django-admin startproject geeks_site

 Change directory to geeks_sitecd geeks_site


 Start the server- Start the server by typing following command in cmd-python manage.py
runserver

Python with Django


 Django
 Flask
 Cherrypy

Django

Django is a Python-based web framework which allows you to quickly create web application without all of the
installation or dependency problems that you normally will find with other frameworks.
When you’re building a website, you always need a similar set of components: a way to handle user
authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to
upload files, etc. Django gives you ready-made components to use.

CHAPTER 4

APPLICATION AND CASE STUDY


Case Study:Hotel Management System

 The project, Hotel Management System is a web-based application that allows the hotel manager to
handle all hotel activities online. Interactive GUI and the ability to manage various hotel bookings and
rooms make this system very flexible and convenient. Customers can view and book room online.
 In this project front end is designed using Django and in back end SQlite3 is used.

Front page
Check in
Show guest list
Check out
Get information of guest exit

The software project contributors are required to install the dependencies as follows:

1. If you want to install system wide:

sudo pip install -r requirements.txt

2. If you want to use virtualenv:

 Create a virtual environment as (you can use any name of the environment as you like):

virtualenv -p python3 hms-virtual-env

 Then execute this:

source hms-virtual-env/bin/activate

 The install requirements as:

pip install -r requirements.txt


Note: To deactivate virtualenv, execute
deactivate

Finally:

 Go to Hotel-Management-System folder that you cloned before.


 Execute the followings:

python3 manage.py migrate


Then,
python3 manage.py runserver

 This will work if correctly set up.

Front page
Front page: coding

Check in

Show Guest list

Recipt

Check out
Get info of guest

Code:-
admin.py

from django.contrib import admin

from .models import *

# Register your models here.

@admin.register(Staff)
class StaffAdmin(admin.ModelAdmin):

# To show in admin app

list_display = (

'staff_id',

'user',

'first_name',

'middle_name',

'last_name',

'contact_no',

'address',

'email_address',

# Adding search bar

search_fields = [

'staff_id',

'user',

'first_name',

'middle_name',

'last_name',
'contact_no',

'address',

'email_address',

# Categorizing the fields

fieldsets = (

(None, {

'fields': ('profile_picture', ('first_name', 'middle_name', 'last_name'),)

}),

('Contact Information', {

'fields': (('contact_no', 'email_address'), 'address')

})

@admin.register(Customer)

class CustomerAdmin(admin.ModelAdmin):

list_display = (

'customer_id',

'first_name',
'middle_name',

'last_name',

'contact_no',

'address',

'email_address',

search_fields = [

'customer_id',

'first_name',

'middle_name',

'last_name',

'contact_no',

'address',

'email_address',

fieldsets = (

(None, {

'fields': (('first_name', 'middle_name', 'last_name'),)


}),

('Contact Information', {

'fields': (('contact_no', 'email_address'), 'address')

})

@admin.register(Reservation)

class ReservationAdmin(admin.ModelAdmin):

list_display = (

'reservation_id',

'customer',

'staff',

'no_of_children',

'no_of_adults',

'reservation_date_time',

'expected_arrival_date_time',

'expected_departure_date_time',

)
@admin.register(Room)

class RoomAdmin(admin.ModelAdmin):

list_display = (

'room_no',

'room_type',

'reservation',

'availability',

'display_facility',

# Adding filter

list_filter = ('room_type', 'availability')

filter_horizontal = ('facility',)

fields = (('room_no', 'room_type'), 'reservation', 'facility')

search_fields = [

'reservation__customer__first_name',

'reservation__customer__middle_name',

'reservation__customer__last_name',

]
@admin.register(Facility)

class FacilityAdmin(admin.ModelAdmin):

list_display = ('name', 'price')

@admin.register(RoomType)

class RoomTypeAdmin(admin.ModelAdmin):

list_display = ('name', 'price')

views.py

from django.contrib.auth.decorators import permission_required

from django.contrib.auth.mixins import PermissionRequiredMixin

from django.contrib.auth.models import User, Group

from django.core.exceptions import ValidationError

from django.db import transaction, IntegrityError

from django.http import Http404

from django.shortcuts import render, redirect, get_object_or_404 # For displaying in template

from django.urls import reverse_lazy

from django.utils import timezone


from django.utils.translation import ugettext_lazy as _

from django.views import generic

from .forms import Signup, ReservationForm, CheckInRequestForm

from .models import Room, Reservation, Customer, Staff # Import Models

def index(request):

"""

This is the view for homepage.

This is a function based view.

"""

page_title = _("Hotel Management System") # For page title as well as heading

total_num_rooms = Room.objects.all().count()

available_num_rooms = Room.objects.exclude(reservation__isnull=False).count()

total_num_reservations = Reservation.objects.all().count()

total_num_staffs = Staff.objects.all().count()

total_num_customers = Customer.objects.all().count()

if total_num_reservations == 0:
last_reserved_by = Reservation.objects.none()

else:

last_reserved_by = Reservation.objects.get_queryset().latest('reservation_date_time')

return render(

request,

'index.html',

# context is whatever sent to the template.

# the index of the dictionary i.e. title in 'title': page_title

# is used as variable in templates

# where as the next one is the variable of this function

'title': page_title,

'total_num_rooms': total_num_rooms,

'available_num_rooms': available_num_rooms,

'total_num_reservations': total_num_reservations,

'total_num_staffs': total_num_staffs,

'total_num_customers': total_num_customers,

'last_reserved_by': last_reserved_by,

}
)

@transaction.atomic

def signup(request):

title = "Signup"

if request.user.is_authenticated:

request.session.flush()

if request.method == 'POST':

form = Signup(request.POST)

if form.is_valid():

try:

with transaction.atomic():

staffs_group = get_object_or_404(Group, name__iexact="Staffs")

form.save()

staff_id = form.cleaned_data['staff_id']

username = form.cleaned_data['username']

s = get_object_or_404(Staff, staff_id__exact=staff_id)

s.user = get_object_or_404(User, username__iexact=username)


s.user.set_password(form.cleaned_data['password1'])

s.user.groups.add(staffs_group)

s.user.save()

s.save()

except IntegrityError:

raise Http404

return redirect('index')

else:

form = Signup()

return render(

request,

'signup.html', {

'form': form, 'title': title},

@permission_required('main.add_reservation', 'login', raise_exception=True)

@transaction.atomic

def reserve(request):
title = "Add Reservation"

reservation = Reservation.objects.none()

if request.method == 'POST':

reservation_form = ReservationForm(request.POST)

if reservation_form.is_valid():

try:

with transaction.atomic():

customer = Customer(

first_name=reservation_form.cleaned_data.get('first_name'),

middle_name=reservation_form.cleaned_data.get('middle_name'),

last_name=reservation_form.cleaned_data.get('last_name'),

email_address=reservation_form.cleaned_data.get('email'),

contact_no=reservation_form.cleaned_data.get('contact_no'),

address=reservation_form.cleaned_data.get('address'),

customer.save()

staff = request.user

reservation = Reservation(

staff=get_object_or_404(Staff, user=staff),
customer=customer,

no_of_children=reservation_form.cleaned_data.get('no_of_children'),

no_of_adults=reservation_form.cleaned_data.get('no_of_adults'),

expected_arrival_date_time=reservation_form.cleaned_data.get('expected_arrival_date_time'),

expected_departure_date_time=reservation_form.cleaned_data.get('expected_departure_date_time'),

reservation_date_time=timezone.now(),

reservation.save()

for room in reservation_form.cleaned_data.get('rooms'):

room.reservation = reservation

room.save()

except IntegrityError:

raise Http404

return render(

request,

'reserve_success.html', {

'reservation': reservation,

)
else:

reservation_form = ReservationForm()

return render(

request,

'reserve.html', {

'title': title,

'reservation_form': reservation_form,

def reserve_success(request):

pass

# For generic ListView or DetailView, the default templates should be stored in


templates/{{app_name}}/{{template_name}}

# By default template_name = modelName_list || modelName_detail.

# eg room_list, room_detail
# @permission_required('main.can_view_staff')

class RoomListView(PermissionRequiredMixin, generic.ListView):

"""

View for list of rooms.

Implements generic ListView.

"""

model = Room # Chooses the model for listing objects

paginate_by = 5 # By how many objects this has to be paginated

title = _("Room List") # This is used for title and heading

permission_required = 'main.can_view_room'

# By default only objects of the model are sent as context

# However extra context can be passed using field extra_context

# Here title is passed.

extra_context = {'title': title}

# By default:

# template_name = room_list
# if you want to change it, use field template_name

# here don't do this, since it is already done as default.

# for own views, it can be done.

def get_queryset(self):

filter_value = self.request.GET.get('filter', 'all')

if filter_value == 'all':

filter_value = 0

elif filter_value == 'avail':

filter_value = 1

try:

new_context = Room.objects.filter(availability__in=[filter_value, 1])

except ValidationError:

raise Http404(_("Wrong filter argument given."))

return new_context

def get_context_data(self, **kwargs):

context = super(RoomListView, self).get_context_data(**kwargs)

context['filter'] = self.request.GET.get('filter', 'all')

return context
class RoomDetailView(PermissionRequiredMixin, generic.DetailView):

"""

View for detail of room

Implements generic DetailView

"""

# The remaining are same as previous.

model = Room

title = _("Room Information")

permission_required = 'main.can_view_room'

extra_context = {'title': title}

class ReservationListView(PermissionRequiredMixin, generic.ListView, generic.FormView):

"""

View for list of reservations.

Implements generic ListView.

"""
model = Reservation

# queryset field selects the objects to be displayed by the query.

# Here, the objects are displayed by reservation date time in descending order

queryset = Reservation.objects.all().order_by('-reservation_date_time')

title = _("Reservation List")

paginate_by = 5

allow_empty = True

form_class = CheckInRequestForm

success_url = reverse_lazy('check_in-list')

permission_required = 'main.can_view_reservation'

extra_context = {'title': title}

@transaction.atomic

def form_valid(self, form):

try:

with transaction.atomic():

checkin = form.save(commit=False)

checkin.user = self.request.user

checkin.save()

except IntegrityError:
raise Http404

return super().form_valid(form)

class ReservationDetailView(PermissionRequiredMixin, generic.DetailView):

"""

View for detail of reservation

Implements generic DetailView

"""

model = Reservation

title = _("Reservation Information")

permission_required = 'main.can_view_reservation'

raise_exception = True

extra_context = {'title': title}

class CustomerDetailView(PermissionRequiredMixin, generic.DetailView):

"""

View for detail of customer


Implements generic DetailView

"""

model = Customer

title = _("Customer Information")

permission_required = 'main.can_view_customer'

raise_exception = True

extra_context = {'title': title}

class StaffDetailView(PermissionRequiredMixin, generic.DetailView):

"""

View for detail of staff

Implements generic DetailView

"""

model = Staff

title = _("Staff Information")

permission_required = 'main.can_view_staff_detail'

extra_context = {'title': title}


class ProfileView(generic.TemplateView):

template_name = 'profile.html'

title = "Profile"

extra_context = {'title': title}

def get_context_data(self, **kwargs):

context = super().get_context_data(**kwargs)

if self.request.user.is_authenticated:

context['information'] = get_object_or_404(Staff, user=self.request.user)

context['user_information'] = self.request.user

else:

raise Http404("Your are not logged in.")

return context

"""

@permission_required('main.add_reservation', 'login', raise_exception=True)

@transaction.atomic

def reserve(request):
title = "Add reservation"

if request.method == 'POST':

try:

with transaction.atomic():

reservation_form = ReservationForm(request.POST)

try:

with transaction.atomic():

customer = Customer(

first_name=reservation_form.cleaned_data.get('first_name'),

middle_name=reservation_form.cleaned_data.get('middle_name'),

last_name=reservation_form.cleaned_data.get('last_name'),

email_address=reservation_form.cleaned_data.get('email'),

address=reservation_form.cleaned_data.get('address'),

customer.save()

except IntegrityError:

print("Cannot add customer")

staff = request.user

reservation = reservation_form.save(commit=False)
reservation.staff = staff

reservation.customer = customer

reservation.reservation_date_time = timezone.now()

reservation.save()

except IntegrityError:

print("Cannot made reservation")

else:

reservation_form = ReservationForm()

return render(

request,

'reserve.html', {

'title': title,

'reservation_form': reservation_form,

"""

urls.py

from django.contrib.auth.decorators import login_required


from django.urls import path

from . import views

urlpatterns = [

# The field option name, should be unique as it is a unique identifier.

# e.g. if you want to use the hyperlink of index page, don't use hardcoded url like

# href="/main/" as if it is changed we have to change all the occurrences of it.

# to solve this, use the value from name field. for above example use

# href="{% url 'index' %}

path('', views.index, name='index'),

path('signup/', views.signup, name='signup'),

path('rooms/', views.RoomListView.as_view(), name='rooms'), # List of Rooms

path('reservations/', views.ReservationListView.as_view(), name='reservations'), # List of Reservations

# <int:pk> takes the argument sent in urls.

path('room/<int:pk>', views.RoomDetailView.as_view(), name='room-detail'), # Detail of each room

# Detail of each reservation

path('reservation/<str:pk>', views.ReservationDetailView.as_view(), name='reservation-detail'),

path('customer/<str:pk>', views.CustomerDetailView.as_view(), name='customer-detail'), # Detail of each


customer
path('staff/<str:pk>', views.StaffDetailView.as_view(), name='staff-detail'), # Detail of staff

path('profile/', login_required(views.ProfileView.as_view()), name='profile'),

path('reserve/', views.reserve, name='reserve'), # For reservation

Models.py

from django.contrib.auth.models import User

from django.db import models

from django.urls import reverse

from django.utils import timezone

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible

class Staff(models.Model):

""" Model for staffs """

profile_picture = models.ImageField(upload_to='staff_img/', default='images/staff.png')

staff_id = models.AutoField(primary_key=True)

first_name = models.CharField(max_length=50)

middle_name = models.CharField(max_length=50, null=False, blank=True)

last_name = models.CharField(max_length=50)
contact_no = models.CharField(max_length=15)

address = models.CharField(max_length=100)

email_address = models.EmailField()

user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, editable=False)

class Meta:

ordering = ['first_name', 'middle_name', 'last_name']

permissions = (("can_view_staff", "Can view staff"), ('can_view_staff_detail', 'Can view staff detail'))

def __str__(self): # Unicode support

return '({0}) {1} {2}'.format(self.staff_id, self.first_name, self.last_name)

@python_2_unicode_compatible

class Customer(models.Model):

"""Model for customers"""

customer_id = models.AutoField(primary_key=True)

first_name = models.CharField(max_length=50)

middle_name = models.CharField(max_length=50, null=False, blank=True)


last_name = models.CharField(max_length=50)

contact_no = models.CharField(max_length=15)

address = models.CharField(max_length=100)

email_address = models.EmailField(null=True, blank=True)

class Meta:

ordering = ['first_name', 'middle_name', 'last_name']

permissions = (('can_view_customer', 'Can view customer'),)

def get_absolute_url(self):

"""

This generates the url for customer detail.

'customer-detail' is the name of the url.

Takes argument customer_id

"""

return reverse('customer-detail', args=str([self.customer_id]))

def __str__(self):

return '({0}) {1} {2}'.format(self.customer_id, self.first_name, self.last_name)


@python_2_unicode_compatible

class Reservation(models.Model):

"""Models for reservations"""

reservation_id = models.AutoField(primary_key=True)

customer = models.ForeignKey(Customer, on_delete=models.CASCADE)

staff = models.ForeignKey(Staff, on_delete=models.CASCADE, editable=False)

no_of_children = models.PositiveSmallIntegerField(default=0)

no_of_adults = models.PositiveSmallIntegerField(default=1)

reservation_date_time = models.DateTimeField(default=timezone.now)

expected_arrival_date_time = models.DateTimeField(default=timezone.now)

expected_departure_date_time = models.DateTimeField(default=timezone.now)

class Meta:

permissions = (('can_view_reservation', 'Can view reservation'),

('can_view_reservation_detail', 'Can view reservation detail'),)

def get_absolute_url(self):

return reverse('reservation-detail', args=str([self.reservation_id]))


def __str__(self):

return '({0}) {1} {2}'.format(self.reservation_id, self.customer.first_name, self.customer.last_name)

@python_2_unicode_compatible

class Room(models.Model):

room_no = models.CharField(max_length=10, primary_key=True)

room_type = models.ForeignKey('RoomType', null=False, blank=True, on_delete=models.CASCADE)

availability = models.BooleanField(default=0)

reservation = models.ForeignKey(Reservation, null=True, blank=True, on_delete=models.SET_NULL)

facility = models.ManyToManyField('Facility')

class Meta:

ordering = ['room_no', ]

permissions = (('can_view_room', 'Can view room'),)

def __str__(self):

return "%s - %s - Rs. %i" % (self.room_no, self.room_type.name, self.room_type.price)


def display_facility(self):

"""

This function should be defined since facility is many-to-many relationship

It cannot be displayed directly on the admin panel for list_display

"""

return ', '.join([facility.name for facility in self.facility.all()])

display_facility.short_description = 'Facilities'

def get_absolute_url(self):

return reverse('room-detail', args=[self.room_no])

def save(self, *args, **kwargs): # Overriding default behaviour of save

if self.reservation: # If it is reserved, than it should not be available

self.availability = 0

else:

self.availability = 1

super().save(*args, **kwargs)
@python_2_unicode_compatible

class Facility(models.Model):

name = models.CharField(max_length=25)

price = models.PositiveSmallIntegerField()

class Meta:

verbose_name_plural = 'Facilities' # Otherwise admin panel shows Facilitys

def __str__(self):

return self.name

@python_2_unicode_compatible

class RoomType(models.Model):

name = models.CharField(max_length=25)

price = models.PositiveSmallIntegerField()

def __str__(self):
return self.name

templates:-

{% extends 'base.html' %}

{% block content-title %}

<h1>{{ title }}</h1>

{% endblock %}

<!-- customer checkin form -->

{% block main-content %}

<div class="container-fluid">

<div class="row">

<div class="col-sm-12 col-md-7">

<div class="panel panel-default">

<div class="panel-body">

<form class="form-horizontal" action="" method="POST">

{% csrf_token %}

<div class="form-group">

<div class="col-sm-2 col-sm-10">

{% for field in form %}


<span class="text-danger small">{{ field.errors }}</span>

<label class="control-label col-sm-2">{{ field.label_tag }}</label>

<div class="col-sm-10">{{ field }}</div>

{% endfor %}

<div class="col-sm-10">{{ datefield }}</div>

<button type="submit" class="btn btn-success">Submit</button>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

{% endblock %}
CHAPTER 5

CONCLUSION

Django is excellent for small, quick web applications, and since it runs on more platforms than any other
Python web development toolkit, it is a good choice where portability is the prime concern.
Obviously we haven’t been able to give Django the depth of discussion it warrants, but it’s fair to say that
almost anything that can be done using the C language and Tk can be done using Python and django. One
example is the Python megawidgets (PMW) package mentioned previously; this is a pure Python package that
creates an excellent widget set by building on the core Django widgets.
REFERENCES

1. Two scoops of Django for 1.11

by Daniel Greenfeld’s and Audrey Greenfield

2. Lightweight Django

by Elman and Mark Lavin

3. High Performance Django

by Peter Baumgartner and Yann Malet

4.Mastering Django: Core – The Complete Guide to Django 1.8 LTS

by Nigel Georg

5.Django Unleashed

by Andrew Pinkham

6. Test-Driven Development with Django

by Kevin Harvey

7.The Definitive Guide to Django: Web Development Done Right

by Adrian Holovaty and Jacob Kaplan-Moss

8. Django for Beginners: Build websites with Python and Django

You might also like