0% found this document useful (0 votes)
2K views45 pages

Industrial Training On: "Python With Django"

The document provides an introduction to Python and Django. It discusses that Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability through significant whitespace. Python supports multiple programming paradigms like procedural, object-oriented, and functional programming. It also has a comprehensive standard library. The document then provides a brief introduction to Django, which is a Python web framework. It discusses Django's Model-View-Template structure and some of its core components like views.

Uploaded by

sai thesis
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)
2K views45 pages

Industrial Training On: "Python With Django"

The document provides an introduction to Python and Django. It discusses that Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability through significant whitespace. Python supports multiple programming paradigms like procedural, object-oriented, and functional programming. It also has a comprehensive standard library. The document then provides a brief introduction to Django, which is a Python web framework. It discusses Django's Model-View-Template structure and some of its core components like views.

Uploaded by

sai thesis
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/ 45

Industrial Training

on
“PYTHON WITH DJANGO”

A Industrial Training Report submitted to the

RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA, BHOPAL

in partial fulfillment of the requirements for the award of the degree of

BACHELOR OF ENGINEERING
IN
INFORMATION TECHNOLOGY

Submitted by

NAWIN KUMAR (0105IT161060)

DEPARTMENT OF INFORMATION TECHNOLOGY

ORIENTAL INSTITUTE OF SCIENCE & TECHNOLOGY


BHOPAL (M.P.)-462021, INDIA
2019-20
ACKNOWLEDGEMENT

We wish to express our profound gratitude to Prof. Atul Barve, Training In-charge,
Department of Information Technology, Oriental Institute of Science and Technology
Bhopal for his invaluable guidance, sustained help and inspiration in carrying out the work.

We sincerely thank Dr. Manish Sawale, Head of Information Technology Department,


OIST Bhopal for his co-operation and guidance during the Industrial Training.

We wish to express our deep gratitude to Dr. K G Sudhakar, Director, OIST Bhopal for his
kind permission to carry out the work at Appin Technology Bhopal.

Finally we would like to thank all the faculty members, staff and other persons who directly
or indirectly helped us in carrying out this project work.

Nawin Kumar (0105IT161060)

i
ABSTRACT

Django is a widely-used Python web application framework with a "batteries-included"


philosophy. The principle behind batteries-included is that the common functionality for
building web applications should come with the framework instead of as separate libraries.
For example, authentication, URL routing, a template engine, an object-relational
mapper (ORM), and database schema migrations (as of version 1.7) are all included with
the Django framework. Compare that included functionality to the Flask framework which
requires a separate library such as Flask-Login to perform user authentication.

The batteries-included and extensibility philosophies are simply two different ways to tackle
framework building. Neither philosophy is inherently better than the other one.

The Django project's stability, performance and community have grown tremendously over
the past decade since the framework's creation. Detailed tutorials and good practices are
readily available on the web and in books. The framework continues to add significant new
functionality such as database migrations with each release.

I highly recommend the Django framework as a starting place for new Python web
developers because the official documentation and tutorials are some of the best anywhere in
software development. Many cities also have Django-specific groups such as Django
District, Django Boston and San Francisco Django so new developers can get help when
they are stuck.

There's some debate on whether learning Python by using Django is a bad idea. However,
that criticism is invalid if you take the time to learn the Python syntax and language
semantics first before diving into web development.

ii
Certificate of Completion

iii
About Organization

Appin Technology Lab is a strategic unit of Tata Consultancy Services focused on


Manufacturing Industries (SMB), Educational Institutions and Examination Boards. TCS
iON provides technology by means of a unique IT-as-a-Service model, offering end-to-end
business solutions. It caters to the needs of multiple industry segments, through innovative,
easy-to-use, secured, integrated, hosted solutions in a build-as-you-grow, pay-as-you-use
business model. TCS iON serves its clients with the help of best practices gained through
TCS' global experience, domestic market reach, skills, and delivery capabilities. TCS iON's
Cloud Based Solution is highly modular, scalable and configurable giving businesses and
educational institutions the benefits of increased efficiencies, faster go to market,
predictability of technology as well as spend and better business results.

Integrated solutions

We as a cloud based solutions offer single-window IT with a pre-integrated suite of


hardware, network, software and services. We ensure that your functions are digitized,
automated and connected. For example, if you are using a CRM solution along with a core
ERP (e.g a Manufacturing ERP) and have a document management system to organize
supporting files and an HRMS, we ensure that these solutions are connected and work as one.
So for you, it is simply one IT and not multiple applications. Integrated applications thus
provide a comprehensive view of business enabling better decisions.

Increased Agility

We bring in the agility to keep pace with changing processes or a new line of business. We
help you configure the processes to work as you currently do or the software recommends
and allows you to choose industry best practices based on your business parameters. TCS
iON gives you increased convenience allowing you to perform various tasks from your

iv
mobile device, no matter where you are. Being automatically compliant with statutory
requirements, the solution ensures your company is always audit ready and legally compliant.

A Pay-as-you-use Model

Our model eliminates capital investment up front as we facilitate procurement of the IT


infrastructure and software on rent for the duration of the contract. Additionally, you only
pay for the number of users who actually use the solution. Thus, you pay as you use on a
monthly basis which includes maintenance and training. Typically, with the TCS iON cloud
based solutions, the ROI exceeds rental within three months, when best practices are well
followed.

Personalized Solutions

Although TCS iON is a cloud service for education, exam boards and manufacturing, the
software is configurable to each sector. You will always get the flavor of your business by
picking and choosing what processes you would need. Furthermore, the multilingual
capability of the solution allows you to customize the solution label names to read in
vernacular languages (like Hindi, Marathi, Tamil etc) enabling users to learn and operate the
solution with ease.

Auto Upgrades

We continuously invest in our cloud based solutions to incorporate best practices. The
solution is constantly enriched based on user feedback and industry and statutory changes.
You will get the upgrades without disrupting your business operations or any additional cost.
Being in perpetual beta ensures that there is no technology obsolescence.

v
Enhanced Business Continuity

Our solution offers optimal performance in normal broadband connectivity along with a
stringent security mechanism to ensure your data privacy is maintained. The capacity of the
TCS iON cloud based solution grows with your increasing computing needs and reduces the
need for IT staff. The solution is resilient to failures as the service works from back-up data
centers in the event of a disaster, ensuring continuity of business operations.

vi
TABLE OF CONTENTS

Acknowledgements ……………………………………………………………………………. i
Abstract ……………………………………………………………………………………….. ii
Certificate of Completion …………………………………………………………………….. iii
About Organization ………………………………………………………………………… iv

1. Python Introduction ……………………………………… 8


2. Django Introduction ……………………………………… 10
3. Installation ……………………………………… 14
4. Strings in Python ……………………………………… 16
5. List in Python ……………………………………… 21
6. Tuples in Python ……………………………………… 27
7. Object Oriented 29
Programming in Python ….……………………………………
8. Django Introduction 32
and Installation ………………………………………..
9. Django Templates ………………………………………… 34
10. Django Project MVT
Structure ………………………………………. 36
11. Views in Django …………………………………….... 37
12. Cocnlusion ………………………………………. 39

vii
Python Introduction

Python is an interpreted, high-level, general-purpose programming language. Created


by Guido van Rossum and first released in 1991, Python's design philosophy
emphasizes code readability with its notable use of significant whitespace. Its language
constructs and object-oriented approach aim to help programmers write clear, logical code
for small and large-scale projects.

Python is dynamically typed and garbage-collected. It supports multiple programming


paradigms, including procedural, object-oriented, and functional programming. Python is
often described as a "batteries included" language due to its comprehensive standard library.

Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0,
released in 2000, introduced features like list comprehensions and a garbage
collection system capable of collecting reference cycles. Python 3.0, released in 2008, was a
major revision of the language that is not completely backward-compatible, and much
Python 2 code does not run unmodified on Python 3. Due to concern about the amount of
code written for Python 2, support for Python 2.7 (the last release in the 2.x series) was
extended to 2020. Language developer Guido van Rossum shouldered sole responsibility for
the project until July 2018 but now shares his leadership as a member of a five-person
steering council.

The Python 2 language, i.e. Python 2.7.x, is "sunsetting" on January 1, 2020, and the Python
team of volunteers will not fix security issues, or improve it in other ways after that
date. With the end-of-life, only Python 3.5.x and later will be supported.

History

viii
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC language (itself inspired
by SETL), capable of exception handling and interfacing with the Amoeba operating
system. Its implementation began in December 1989. Van Rossum continued as Python's
lead developer until July 12, 2018, when he announced his "permanent vacation" from his
responsibilities as Python's Benevolent Dictator For Life, a title the Python community
bestowed upon him to reflect his long-term commitment as the project's chief decision-
maker. In January, 2019, active Python core developers elected Brett Cannon, Nick Coghlan,
Barry Warsaw, Carol Willing and Van Rossum to a five-member "Steering Council" to lead
the project.

Python 2.0 was released on 16 October 2000 with many major new features, including
a cycle-detecting garbage collector and support for Unicode.

Python 3.0 was released on 3 December 2008. It was a major revision of the language that is
not completely backward-compatible. Many of its major features were backported to Python
2.6.x and 2.7.x version series. Releases of Python 3 include the 2to3 utility, which automates
(at least partially) the translation of Python 2 code to Python 3.

Python 2.7's end-of-life date was initially set at 2015 then postponed to 2020 out of concern
that a large body of existing code could not easily be forward-ported to Python 3.

Python is a multi-paradigm programming language. Object-oriented


programming and structured programming are fully supported, and many of its features
support functional programming and aspect-oriented programming (including
by metaprogramming and metaobjects (magic methods)). Many other paradigms are
supported via extensions, including design by contract and logic programming.

Python uses dynamic typing, and a combination of reference counting and a cycle-detecting
garbage collector for memory management. It also features dynamic name resolution (late
binding), which binds method and variable names during program execution.

Python's design offers some support for functional programming in the Lisp tradition. It
has filter, map, and reduce functions; list comprehensions, dictionaries, sets

ix
and generator expressions. The standard library has two modules (itertools and functools)
that implement functional tools borrowed from Haskell and Standard ML.

The language's core philosophy is summarized in the document The Zen of Python (PEP 20),
which includes aphorisms such as:

 Beautiful is better than ugly.


 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Readability counts.

Django Introduction

Django is a free and open source web application framework written in Python. A
framework is nothing more than a collection of modules that make development easier. They
are grouped together, and allow you to create applications or websites from an existing
source, instead of from scratch.

This is how websites - even simple ones designed by a single person - can still include
advanced functionality like authentication support, management and admin panels, contact
forms, comment boxes, file upload support, and more. In other words, if you were creating a
website from scratch you would need to develop these components yourself. By using a
framework instead, these components are already built, you just need to configure them
properly to match your site.

The official project site describes Django as "a high-level Python Web framework that
encourages rapid development and clean, pragmatic design. Built by experienced developers,
it takes care of much of the hassle of Web development, so you can focus on writing your
app without needing to reinvent the wheel. It’s free and open source."

x
Django offers a big collection of modules which you can use in your own projects. Primarily,
frameworks exist to save developers a lot of wasted time and headaches and Django is no
different.

You might also be interested in learning that Django was created with front-end developers
in mind. "Django’s template language is designed to feel comfortable and easy-to-learn to
those used to working with HTML, like designers and front-end developers. But it is also
flexible and highly extensible, allowing developers to augment the template language as
needed."

If you're going to be working with Python, especially for web applications or web design,
you'll want to remember the Django framework. It will certainly come in handy.

Python stands out because it is easy to learn and easy to understand. Many consider Ruby a
great place to start, like Python, yet the latter has a four-year head start. This means that it
has a big foothold in the enterprise world, and it's much more popular with C developers.
This is because it's easy to crossover between the two languages.

Both Ruby and Python share a significant amount of growth in the job market, so choosing
either language would be beneficial in terms of a career. PHP is also used often though the
application is different.

Ultimately, it comes down to what you will be developing, as each language has its niche.

What are the Languages Used for?


PHP is a server scripting language that is primarily used to create dynamic and interactive
websites. It is the best language for creating HTML content, and can be used to build
anything from a simple blog to a huge, corporate style website.

Python is a high-level, object-oriented general-purpose language, that is versatile and can be


xi
used for nearly anything. It is commonly used to develop web and mobile applications,
website crawlers, indexers, daemons, and desktop GUI apps.

Ruby is a high-level, object-oriented language that is used to work with web application and
data entities; it exists to take the focus away from query tasks. Ruby is most famous for its
dynamic type system which performs type checking during runtime. It also features
automatic memory management.

Out of the three languages, Python is the best for absolute beginners and is often
recommended by programmers because it uses a syntax that emphasizes simplicity and ease
of use. Whereas, Ruby is better used by programmers that have experience with other
languages. PHP, on the other hand, is best suited for developers who are used to working
with C languages.

They all have specific purposes and use-cases as you can see from the descriptions. To
provide a better understanding, we'll offer some examples of who uses these languages.

Who Uses PHP?


In short, PHP was designed for web development and the creation of dynamic web pages.
Brands that use PHP to power their products include:

 Udemy
 Wikipedia
 Facebook
 Google
 NASA

Who Uses Python?


In short, Python was designed to emphasize productivity, readability, and ease of use.
Brands that use Python to power their products include:
xii
 YouTube
 Google
 Yahoo! Map
 Shopzilla
 Ultraseek

Who Uses Ruby?


In short, Ruby was designed specifically for programmers to make the development process
more fun and flexible. Brands that use Ruby to power their products include:

 Twitter
 Hulu
 Groupon
 IndieGoGo
 GitHub

It doesn't matter who you ask, the answer to this question will always be the same. There is
no "best" in the world of programming because each language serves a purpose. To make it
even more confusing, with the three languages discussed here, you can do just about
anything as they're all general purpose languages.

There is no right or wrong answer.

Also, there are frameworks available for each one of these languages, and those make
development easier. PHP has several content management systems like WordPress, Drupal,
and Joomla. Python has Django and CherryPy. Finally, Ruby has Rails or Ruby on Rails.

You can't go wrong with any of them. Of course, we recommend starting with Python.

xiii
Installation

To get started working with Python 3, you’ll need to have access to the Python interpreter.
There are several common ways to accomplish this:

 Python can be obtained from the Python Software Foundation website at python.org.
Typically, that involves downloading the appropriate installer for your operating
system and running it on your machine.
 Some operating systems, notably Linux, provide a package manager that can be run
to install Python.
 On macOS, the best way to install Python 3 involves installing a package manager
called Homebrew. You’ll see how to do this in the relevant section in the tutorial.
 On mobile operating systems like Android and iOS, you can install apps that provide a
Python programming environment. This can be a great way to practice your coding
skills on the go.

Alternatively, there are several websites that allow you to access a Python interpreter online
without installing anything on your computer at all.

Windows

It is highly unlikely that your Windows system shipped with Python already installed.
Windows systems typically do not. Fortunately, installing does not involve much more than
downloading the Python installer from the python.org website and running it. Let’s take a
look at how to install Python 3 on Windows:

1. Open a browser window and navigate to the Download page for


Windows at python.org.
xiv
2. Underneath the heading at the top that says Python Releases for Windows, click on
the link for the Latest Python 3 Release - Python 3.x.x.
3. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit
or Windows x86 executable installer for 32-bit.

Step 2: Run the Installer


Once you have chosen and downloaded an installer, simply run it by double-clicking on the
downloaded file. A dialog should appear. Then just click Install Now. That should be all
there is to it. A few minutes later you should have a working Python 3 installation on your
system.

Linux
There is a very good chance your Linux distribution has Python installed already, but it
probably won’t be the latest version, and it may be Python 2 instead of Python 3.

To find out what version(s) you have, open a terminal window and try the following
commands:

 python --version
 python2 --version
 python3 –version

If the version shown is Python 2.x.x or a version of Python 3 that is not the latest (3.6.5 as
of this writing), then you will want to install the latest version. The procedure for doing this
will depend on the Linux distribution you are running.

xv
Strings in Python

In Python, Strings are arrays of bytes representing Unicode characters. However, Python
does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.

Accessing characters in Python

In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.

# Python Program to Access


# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

xvi
String Slicing

To access a range of characters in the String, method of slicing is used. Slicing in a String is
done by using a Slicing operator (colon).

# Python Program to
# demonstrate String slicing

# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Deleting/Updating from a String

In Python, Updation or deletion of characters from a String is not allowed. This will cause
an error because item assignment or item deletion from a String is not supported. Although
deletion of entire String is possible with the use of a built-in del keyword. This is because
Strings are immutable, hence elements of a String cannot be changed once it has been
assigned. Only new strings can be reassigned to the same name.

# Python Program to Update


# character of a String

xvii
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

# Updating a character
# of the String
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)

Deleting Entire String:

Deletion of entire string is possible with the use of del keyword. Further, if we try to print
the string, this will produce an error because String is deleted and is unavailable to be
printed.

# Python Program to Delete


# entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

xviii
Escape Sequencing in Python

While printing Strings with single and double quotes in it causes SyntaxError because
String already contains Single and Double Quotes and hence cannot be printed with the use
of either of these. Hence, to print such a String either Triple Quotes are used or Escape
sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes
are used to represent a string, then all the single quotes present in the string must be escaped
and same is done for Double Quotes.

# Python Program for


# Escape Sequencing
# of String

# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Doule Quotes


String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the


# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

xix
Formatting of Strings

Strings in Python can be formatted with the use of format() method which is very versatile
and powerful tool for formatting of Strings. Format method in String contains curly braces {}
as placeholders which can hold arguments according to position or keyword to specify the
order.

# Python Program for


# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g = 'Geeks', f = 'For', l = 'Life')
print("\nPrint String in order of Keywords: ")
print(String1)

xx
List in Python

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may contain DataTypes
like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered
even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed
according to a definite sequence and the indexing of a list is done with 0 being the first index.
Each element in the list has its definite place in the list, which allows duplicating of elements
in the list, with each element having its own distinct place and credibility.

Creating a List

Lists in Python can be created by just placing the sequence inside the square brackets[].
Unlike Sets, list doesn’t need a built-in function for creation of list.

# Python program to demonstrate


# Creation of List

# Creating a List
List = []
print("Intial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")

xxi
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

# Creating a List with


# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with


# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)

Adding Elements to a List

Using append() method


Elements can be added to the List by using built-in append() function. Only one element at a
time can be added to the list by using append() method, for addition of multiple elements
with the append() method, loops are used. Tuples can also be added to the List with the use
of append method because tuples are immutable. Unlike Sets, Lists can also be added to the
existing list with the use of append() method.

xxii
# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List


# using Iterator
for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List


List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List


List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

xxiii
Using insert() method
append() method only works for addition of elements at the end of the List, for addition of
element at the desired position, insert() method is used. Unlike append() which takes only
one argument, insert() method requires two arguments(position, value).

# Python program to demonstrate


# Addition of elements in a List

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)

Accessing elements from the List

In order to access the list items refer to the index number.Use the index operator [ ] to access
an item in a list.The index must be an integer.Nested list are accessed using nested indexing.

# Python program to demonstrate


# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


xxiv
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'] , ['Geeks']]

# accessing a element from the


# Multi-Dimensional List using
# index number
print("Acessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Removing Elements from the List

Using remove() method


Elements can be removed from the List by using built-in remove() function but an Error
arises if element doesn’t exist in the set. Remove() method only removes one element at a
time, to remove range of elements, iterator is used. The remove() method removes the
specified item.

# Python program to demonstrate


# Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)

# Removing elements from List


# using Remove() method
xxv
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

# Removing elements from List


# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

xxvi
Tuples in Python

A Tuple is a collection of Python objects separated by commas. In someways a tuple is


similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable
unlike lists which are mutable.

# Creating non-empty tuples

# One way of creation


tup = 'python', 'geeks'
print(tup)

# Another for doing the same


tup = ('python', 'geeks')
print(tup)

Concatenation of Tuples

# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')

# Concatenating above two


print(tuple1 + tuple2)

Nesting of Tuples

# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)

xxvii
Immutable Tuples

#code to test that tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Deleting a Tuple

# Code for deleting a tuple

tuple3 = ( 0, 1)
del tuple3
print(tuple3)

Finding Length of a Tuple

# Code for printing the length of a tuple

tuple2 = ('python', 'geek')


print(len(tuple2))

Converting list to a Tuple

# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'

Takes a single parameter which may be a list,string,set or even a dictionary( only keys are
taken as elements) and converts them to a tuple.

xxviii
Object Oriented Programming in Python

Below is a simple Python program that creates a class with single method.

# A simple example class


class Test:

# A sample method
def fun(self):
print("Hello")

# Driver code
obj = Test()
obj.fun()

As we can see above, we create a new class using the class statement and the name of the
class. This is followed by an indented block of statements which form the body of the class.
In this case, we have defined a single method in the class.

Next, we create an object/instance of this class using the name of the class followed by a
pair of parentheses.

The self
1. Class methods must have an extra first parameter in method definition. We do not give
a value for this parameter when we call the method, Python provides it
2. If we have a method which takes no arguments, then we still have to have one
argument – the self. See fun() in above simple example.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.

The __init__ method


The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object

xxix
of a class is instantiated. The method is useful to do any initialization you want to do with
your object.

Class and Instance Variables (Or attributes)

In Python, instance variables are variables whose value is assigned inside a constructor or
method with self.
Class variables are variables whose value is assigned in class.

# Python program to show that the variables with a value


# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Computer Science Student


class CSStudent:

# Class Variable
stream = 'cse'

# The init method or constructor


def __init__(self, roll):

# Instance Variable
self.roll = roll

# Objects of CSStudent class


a = CSStudent(101)
b = CSStudent(102)

print(a.stream) # prints "cse"


print(b.stream) # prints "cse"
print(a.roll) # prints 101

# Class variables can be accessed using class

xxx
# name also
print(CSStudent.stream) # prints "cse"

Data hiding

In Python, we use double underscore (Or __) before the attributes name and those attributes
will not be directly visible outside.

Private methods are accessible outside their class, just not easily accessible. Nothing in
Python is truly private; internally, the names of private methods and attributes are mangled
and unmangled on the fly to make them seem inaccessible by their given names.

Printing Objects

Printing objects gives us information about objects we are working with. In C++, we can do
this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the
class. In Java, we use toString() method. In python this can be achieved by using __repr__ or
__str__ methods.

xxxi
Django Introduction and Installation

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?
1. It’s very easy to switch database in Django framework.
2. It has built-in admin interface which makes easy to work with it.
3. Django is fully functional framework that requires nothing else.
4. It has thousands of additional packages available.
5. 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

xxxii
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 the following command in command prompt-


pip install virtualenv

Django Templates

xxxiii
There are two types of web pages – Static and Dynamic pages. Static webpages are those
pages whose content is static i.e. they don’t change with time. Every time you open that page,
you see the same content. Their content is independent of time, location, user, etc. Dynamic
webpages are those pages whose content are generated dynamically i.e. They vary as per
location, time, user and on various factors.

Django framework efficiently handles and generates dynamically HTML web pages which
are visible to end-user. Django mainly functions with backend so, in order to provide
frontend and provide a layout to our website, we use templates. There are two methods of
adding the template to our website depending on our need.

1. We can use a single template directory which will be spread over the entire project.
2. For each app of our project, we can create a different template directory.
For our current project, we will create a single template directory which will be spread over
the entire project for simplicity. App-level templates are generally used in big projects or in
case we want to provide a different layout to each component of our webpage.

Adding template to project –

Create a template directory in the same directory as our project.


Now, navigate to the directory.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
xxxiv
'django.contrib.messages.context_processors.messages',
],
},
},
]

Now our command will join our BASE_DIR to ‘templates’ and feed it to ‘DIRS’ key of
TEMPLATE. Now, we can our save HTML codes in directory and can access it from our
code.

HttpResponse –

HttpResponse is buitlin utility function provided by django to return HttpResponse to


incoming request. We can write a complete HTML code in HttpResponse function but the
readability of code will be minimal and it will be more difficult to debug. It will be better to
use HTML pages instead of writing complete HTML codes into HttpResponse function.
This is where render function comes into play.

render –

render is builtin utility provided by Django to render HTML pages and to feed dynamic
content into them. render function takes three input parameters normally.
1. First parameter is request parameter which was received by our function.
2. Second parameter is url of an HTML page which will be displayed on screen on
invoking the current function.
3. Third parameter which is optional but very important and which makes our HTML
page dynamic is a dictionary which is sent to HTML page as key-value pair.

xxxv
Django Project MVT Structure

Django is based on MVT (Model-View-Template) architecture. MVT is a software design


pattern for developing a web application.

MVT Structure has the following three parts –

Model: Model is going to act as the interface of your data. It is responsible for maintaining
data. It is the logical data structure behind the entire application and is represented by a
database (generally relational databases such as MySql, Postgres).

View: The View is the user interface — what you see in your browser when you render a
website. It is represented by HTML/CSS/Javascript and Jinja files.

Template: A template consists of static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted.

Project Structure :

A Django Project when initialised contains basic files by default such as manage.py, view.py,
etc. A simple project structure is enough to create a single page application. Here are the
major files and there explanations.

manage.py-This file is used to interact with your project via the command line(start the
server, sync the database… etc). For getting the full list of command that can be executed by
manage.py type this code in the command window-

$ python manage.py help

folder – This folder contains all the packages of your project. Initially it contains four files
xxxvi
 init_.py – It is python package.
 settings.py – As the name indicates it contains all the website settings. In this file we
register any applications we create, the location of our static files, database
configuration details, etc.
 urls.py – In this file we store all links of the project and functions to call.
 wsgi.py – This file is used in deploying the project in WSGI. It is used to help your
Django application communicate with the web server.

Benefits of Django Architecture –


 Rapid Development
 Loosely Coupled
 Ease of Modification

Drawbacks of MVC Architecture –


 Too much load on Model Component
 Development Complexity is high
 Two components are controlling View

Views In Django | Python

According to Django documentation A view function, or view for short, is simply a Python
function that takes a Web request and returns a Web response. This response can be the
HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an
image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary
to return that response. This code can live anywhere you want, as long as it’s on your Python
path. There’s no other requirement–no “magic, ” so to speak. For the sake of putting the
code somewhere, the convention is to put views in a file called views.py, placed in your
project or application directory.
A Django project/ consists of a main folder also know as Django folder which consists
of settings.py and one or more app folders which contains views.py.

xxxvii
Example:

- python manage.py runserver


- python manage.py startapp
- python manage.py migrate
- python manage.py makemigrations

Defining and using views –

Every app in Django project by deafult contains a python file named views.py.
Using views.py, we control what to display user on webpage.
Any function in views.py takes requestparameter by default.
To connect functions defined in views.py, you need to do URL mapping.
Goto geeks_site/urls.py and import ViewDemo fuction from brand/views.py.

In urlpatterns, add a line


path(‘hello-world/’,ViewDemo)

Now, your urls.py is now,

from django.contrib import admin


from django.urls import path

from brand.views import ViewDemo

urlpatterns = [
path('admin/', admin.site.urls),
path('hello-world/', ViewDemo),
]

xxxviii
Now, URL mapping is done. Goto your terminal and start server by using the following
commands:

python manage.py runserver

Conclusion

As an undergraduate of the Oriental Institute of Science and Technology, I would like to say
that this training program was an excellent opportunity for me to get to the ground level and
experience the things that we would have never gained through going straight into a job. I
am grateful to the Oriental Institute of Science and Technology and TCS Ion for giving us
this wonderful opportunity. The main objective of the industrial training is to provide an
opportunity to undergraduates to identify, observe and practice how information technology
is applicable in the real industry.

It is not only to get experience on technical practices but also to observe management
practices and to interact with fellow workers. The only chance that an undergraduate has to
have this experience is the industrial training period. I feel I got the maximum out of that
experience. Also I learnt the way of work in an organization, the importance of being
punctual, the importance of maximum commitment, and the importance of team spirit. The
training program having three destinations was a lot more useful than staying at one place
throughout the whole six months. In my opinion, I have gained lots of knowledge and
experience needed to be successful in a great information technology challenge, as in my
opinion, IT is after all a Challenge, and not a Job.

xxxix
Print
 RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA, BHOPAL
(University of Technology of Madhya Pradesh)
EXAMINATION ADMIT CARD (EAC)
December 2019

Time
10:00AM to 01:00PM
:
Roll No. : 0105IT161055 Status : Regular
Please Mr. MAYANK KUMAR AGRAWAL   S/O  Mr. UMESH
Admit KUMAR AGRAWAL
to the BE, Information Technology Semester VII
Examination  in the following Subject(s):
[0105] Oriental Institute of Science &
Centre :
Technology,Bhopal
Subjects & Code New Scheme
Theory : Practical (s) :
IT7001 - Cloud Computing IT7001 - Cloud Computing
IT7002 - Object Oriented Analysis & IT7002 - Object Oriented Analysis &
Design Design
IT7003 - Wireless & Mobile Computing IT7003 - Wireless & Mobile Computing
IT7004 [2] - Elective-III [E-Commerce & IT7006 - Project-I
Governance] IT7007 - Industrial Training
IT7005 [2] - Elective-IV [Artificial
Intelligence (AI)]
* Provisionally permitted subject to eligibility. Any Discrepancy in candidate’s Name, Father’s Name
etc. Should be Informed to the office of the Controller (Examinations) Immediately.
Important Note :

1. Occupy your seat 15 minutes before commencement of Exam.


2. Please check your exam center carefully.
3. Please read the guideline to fill the OMR Sheet. 

4. Please check date, time, subject code(s) & its title from time table very
CONTROLLER (EXAMS)
carefully
RAJIV GANDHI PROUDYOGIKI
VISHWAVIDYALAYA, BHOPAL
Print
 RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA, BHOPAL
(University of Technology of Madhya Pradesh)
EXAMINATION ADMIT CARD (EAC)
December 2019

Time
10:00AM to 01:00PM
:
Roll No. : 0105IT161029 Status : Regular
Please
Mr. AZAD KHAN   S/O  Mr. LAL KHAN
Admit
to the BE, Information Technology Semester VII
Examination  in the following Subject(s):
[0105] Oriental Institute of Science &
Centre :
Technology,Bhopal
Subjects & Code New Scheme
Theory : Practical (s) :
IT7001 - Cloud Computing IT7001 - Cloud Computing
IT7002 - Object Oriented Analysis & IT7002 - Object Oriented Analysis &
Design Design
IT7003 - Wireless & Mobile Computing IT7003 - Wireless & Mobile Computing
IT7004 [2] - Elective-III [E-Commerce & IT7006 - Project-I
Governance] IT7007 - Industrial Training
IT7005 [2] - Elective-IV [Artificial
Intelligence (AI)]
* Provisionally permitted subject to eligibility. Any Discrepancy in candidate’s Name, Father’s Name
etc. Should be Informed to the office of the Controller (Examinations) Immediately.
Important Note :

1. Occupy your seat 15 minutes before commencement of Exam.


2. Please check your exam center carefully.
3. Please read the guideline to fill the OMR Sheet. 

4. Please check date, time, subject code(s) & its title from time table very
CONTROLLER (EXAMS)
carefully
RAJIV GANDHI PROUDYOGIKI
VISHWAVIDYALAYA, BHOPAL
Print
 RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA, BHOPAL
(University of Technology of Madhya Pradesh)
EXAMINATION ADMIT CARD (EAC)
December 2019

Time
10:00AM to 01:00PM
:
Roll No. : 0105IT161037 Status : Regular
Please Mr. DEVENDRA MAHAJAN   S/O  Mr. SANTOSH
Admit MAHAJAN
to the BE, Information Technology Semester VII
Examination  in the following Subject(s):
[0105] Oriental Institute of Science &
Centre :
Technology,Bhopal
Subjects & Code New Scheme
Theory : Practical (s) :
IT7001 - Cloud Computing IT7001 - Cloud Computing
IT7002 - Object Oriented Analysis & IT7002 - Object Oriented Analysis &
Design Design
IT7003 - Wireless & Mobile Computing IT7003 - Wireless & Mobile Computing
IT7004 [2] - Elective-III [E-Commerce & IT7006 - Project-I
Governance] IT7007 - Industrial Training
IT7005 [2] - Elective-IV [Artificial
Intelligence (AI)]
* Provisionally permitted subject to eligibility. Any Discrepancy in candidate’s Name, Father’s Name
etc. Should be Informed to the office of the Controller (Examinations) Immediately.
Important Note :

1. Occupy your seat 15 minutes before commencement of Exam.


2. Please check your exam center carefully.
3. Please read the guideline to fill the OMR Sheet. 

4. Please check date, time, subject code(s) & its title from time table very
CONTROLLER (EXAMS)
carefully
RAJIV GANDHI PROUDYOGIKI
VISHWAVIDYALAYA, BHOPAL

You might also like