Internet Technology Lab Certificate
Internet Technology Lab Certificate
CERTIFICATE
LAB [CSE 3262] of Third Year B. Tech. (Computer Science and Engineering) Degree at
Date: ……...................................
Signature
Faculty in Charge
CONTENTS
Evaluation plan i
1 JQuery 1–7
2 Bootstrap 8 – 12
3 Python Basics 13 – 31
6 54 – 72
Form Processing using Django
7 Mini-project-Phase-1 73 – 73
8 Databases 74 – 89
9 90 – 90
Mini-project-Phase-2
10 ReST API 91 – 98
11 Mini-project-Phase-3 99-99
12 Mini-project-Phase-3 99-99
13 References 100
Course Objectives
Course Outcomes
At the end of this course, students will be able to
Evaluation plan
• Internal Assessment Marks : 60%
ii
THE STUDENTS SHOULD NOT
• Bring mobile phones or any other electronic gadgets to the lab.
• Go out of the lab without permission.
iii
Lab No:1
Lab No : 1 Date:
JQuery
Objectives:
In this lab, student will be able to
1. Develop responsive web pages using jquery
2. Familiarize with DOM manipulation and animations
jQuery is a fast and concise JavaScript library to develop web based application.
Here is the list of important core features supported by jQuery −
• DOM manipulation − The jQuery made it easy to select DOM elements, negotiate
them and modifying their content by using cross-browser open source selector
engine called Sizzle.
• Event handling − The jQuery offers an elegant way to capture a wide variety of
events, such as a user clicking on a link, without the need to clutter the HTML
code itself with event handlers.
• AJAX Support − The jQuery eases developing a responsive and feature rich site
using AJAX technology.
• Animations − The jQuery comes with plenty of built-in animation effects which
you can use in your websites.
• Lightweight − The jQuery is very lightweight library - about 19KB in size
(Minified and gzipped).
• Cross Browser Support − The jQuery has cross-browser support, and works well
in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
• Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.
Selector:
jQuery offers a very powerful technique for selecting and working on a collection of
elements—CSS selectors. The basic syntax is like this:
$('selector')
use a CSS class selector like this:
$('.submenu')
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").css("background-color", "yellow");
$("#myid").css("background-color", "red");
});
</script>
</head>
<body>
<div>
<p class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
Page 2 of 100
Lab No:1
You can replace a complete DOM element with the specified HTML or DOM elements.
[Link]( content )
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
$(this).replaceWith("<h1>JQuery is Great</h1>");
});
});
</script>
Events
To make your web page interactive, you write programs that respond to events.
Mouse events: click, dblclick, mousedown, mouseup, mouseover, etc
Document/Window Events: load, resize, scroll, unload etc
Form Events: submit, reset, focus, and change
Page 3 of 100
Lab No:1
• The hover( over, out ) method simulates hovering (moving the mouse on, and
off, an object).
<title></title>
<script src="[Link]"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var result = $('input[type="radio"]:checked');
if ([Link] > 0) {
$('#divResult').html([Link]() + " is checked");
}
else {
$('#divResult').html("No radio button checked");
}
});
});
</script>
</head>
<body style="font-family:Arial">
Gender :
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input id="btnSubmit" type="submit" value="submit" />
<div id="divResult">
</div>
</body>
</html>
• The each() method in jQuery is used to execute a function for each matched
element.
<html>
<head>
<title></title>
<script src="[Link]"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var result = $('input[type="checkbox"]:checked');
if ([Link] > 0) {
var resultString = [Link] + " checkboxe(s) checked<br/>";
[Link](function () {
resultString += $(this).val() + "<br/>";
});
$('#divResult').html(resultString);
}
Page 5 of 100
Lab No:1
else {
$('#divResult').html("No checkbox checked");
}
});
});
</script>
</head>
<body style="font-family:Arial">
Skills :
<input type="checkbox" name="skills" value="JavaScript" />JavaScript
<input type="checkbox" name="skills" value="jQuery" />jQuery
<input type="checkbox" name="skills" value="C#" />C#
<input type="checkbox" name="skills" value="VB" />VB
<br /><br />
<input id="btnSubmit" type="submit" value="submit" />
<br /><br />
<div id="divResult">
</div>
</body>
</html>
Exercises:
1. Write a web page which contains table with 3 X 3 dimensions (fill some data) and
one image. Style the rows with alternate color. Move the table and image together from
right to left when button is clicked.
2. Design a calculator to perform basic arithmetic operations. Use textboxes and buttons
to design web page.
Page 6 of 100
Lab No:1
Additional Exercise:
1. Implement the bouncing ball using animate() function.
2. Write a web page which displays image and show the sliding text on the image.
Page 7 of 100
Lab No:2
Bootstrap
Objectives:
• Bootstrap is a free front-end framework for faster and easier web development
• Bootstrap includes HTML and CSS based design templates for typography,
forms, buttons, tables, navigation, modals, image carousels and many other, as
well as optional JavaScript plugins
• Bootstrap also gives you the ability to easily create responsive
designs(automatically adjust themselves to look good on all devices)
Bootstrap Containers are used to pad the content inside of them, and there are
two container classes available:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
Page 8 of 100
Lab No:2
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
<script
src="[Link]
></script>
<script
src="[Link]
ipt>
</head>
<body>
<div class="container">
<p>Resize the browser window to see that its width (max-width) will change at
different breakpoints.</p>
</div>
</body></html>
Bootstrap Tables
Page 9 of 100
Lab No:2
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
<script
src="[Link]
t>
<script
src="[Link]
</head>
<body>
<div class="container">
<h2>Dark Striped Table</h2>
<p>Combine .table-dark and .table-striped to create a dark, striped table:</p>
<table class="table table-dark table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
Page 10 of 100
Lab No:2
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@[Link]</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Exercise:
1. Design the student bio-data form using button, label, textbox, radio button, table and
checkbox.
2. Design a web page which shows the database oriented CRUD operation. Consider
Employee data.
3. Create a web page using bootstrap as mentioned. Divide the page in to 2 parts top and
bottom, then divide the bottom into 3 parts and design each top and bottom part using
Page 11 of 100
Lab No:2
different input groups, input, badges, buttons and button groups. Make the design more
attractive.
Additional Exercise:
1. Design an attractive ‘train ticket booking form’ using different bootstrap elements.
Page 12 of 100
Lab No:3
Python Basics
Objectives:
Python was created by Guido van Rossum in the early 90s. It is now one of the most
popular languages in existence.
####################################################
## 1. Primitive Datatypes and Operators
####################################################
# Integer division rounds down for both positive and negative numbers.
5 // 3 # => 1
-5 // 3 # => -2
5.0 // 3.0 # => 1.0 # works on floats too
-5.0 // 3.0 # => -2.0
Page 13 of 100
Lab No:3
# Modulo operation
7 % 3 # => 1
# Boolean Operators
# Note "and" and "or" are case-sensitive
True and False # => False
False or True # => True
# True and False are actually 1 and 0 but with different keywords
True + True # => 2
True * 8 # => 8
False - 5 # => -5
# Using boolean logical operators on ints casts them to booleans for evaluation, but their
non-cast value is returned
# Don't mix up with bool(ints) and bitwise and/or (&,|)
bool(0) # => False
Page 14 of 100
Lab No:3
# Equality is ==
1 == 1 # => True
2 == 1 # => False
# Inequality is !=
1 != 1 # => False
2 != 1 # => True
# More comparisons
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# (is vs. ==) is checks if two variables refer to the same object, but == checks
# if the objects pointed to have the same values.
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b=a # Point b at what a is pointing to
b is a # => True, a and b refer to the same object
b == a # => True, a's and b's objects are equal
b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
b is a # => False, a and b do not refer to the same object
b == a # => True, a's and b's objects are equal
# String literals (but not variables) can be concatenated without using '+'
"Hello " "world!" # => "Hello world!"
# You can also format using f-strings or formatted string literals (in Python 3.6+)
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
# You can basically put any Python statement inside the braces and it will be output in
the string.
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
# None is an object
None # => None
####################################################
## 2. Variables and Collections
####################################################
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end string.
Page 16 of 100
Lab No:3
Page 17 of 100
Lab No:3
# Get the index of the first item found matching the argument
[Link](2) # => 1
[Link](4) # Raises a ValueError as 4 is not in the list
Page 18 of 100
Lab No:3
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
type((1)) # => <class 'int'>
type((1,)) # => <class 'tuple'>
type(()) # => <class 'tuple'>
# Note keys for dictionaries have to be immutable types. This is to ensure that
# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
Page 19 of 100
Lab No:3
# Get all keys as an iterable with "keys()". We need to wrap the call in list()
# to turn it into a list. We'll talk about those later. Note - for Python
# versions <3.7, dictionary key ordering is not guaranteed. Your results might
# not match the example below exactly. However, as of Python 3.7, dictionary
# items maintain the order at which they are inserted into the dictionary.
list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7
list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+
# Get all values as an iterable with "values()". Once again we need to wrap it
# in list() to get it out of the iterable. Note - Same as above regarding key
# ordering.
list(filled_dict.values()) # => [3, 2, 1] in Python <3.7
list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4 # another way to add to dict
# From Python 3.5 you can also use the additional unpacking options
{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
Page 20 of 100
Lab No:3
Page 21 of 100
Lab No:3
####################################################
## 3. Control Flow and Iterables
####################################################
"""
For loops iterate over lists
prints:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# You can use format() to interpolate formatted strings
print("{} is a mammal".format(animal))
"""
"range(number)" returns an iterable of numbers
from zero to the given number
prints:
0
1
2
3
Page 22 of 100
Lab No:3
"""
for i in range(4):
print(i)
"""
"range(lower, upper)" returns an iterable of numbers
from the lower number to the upper number
prints:
4
5
6
7
"""
for i in range(4, 8):
print(i)
"""
"range(lower, upper, step)" returns an iterable of numbers
from the lower number to the upper number, while incrementing
by step. If step is not indicated, the default value is 1.
prints:
4
6
"""
for i in range(4, 8, 2):
print(i)
"""
To loop over a list, and retrieve both the index and the value of each item in the list
prints:
0 dog
1 cat
2 mouse
"""
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
print(i, value)
"""
While loops go until a condition is no longer met.
prints:
0
Page 23 of 100
Lab No:3
1
2
3
"""
x=0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
# Writing to a file
contents = {"aa": 12, "bb": 21}
with open("[Link]", "w+") as file:
[Link](str(contents)) # writes a string to a file
# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
next(our_iterator) # => "one"
# After the iterator has returned all of its data, it raises a StopIteration exception
next(our_iterator) # Raises StopIteration
# We can also loop over it, in fact, "for" does this implicitly!
our_iterator = iter(our_iterable)
for i in our_iterator:
print(i) # Prints one, two, three
# You can grab all the elements of an iterable or iterator by calling list() on it.
list(our_iterable) # => Returns ["one", "two", "three"]
Page 25 of 100
Lab No:3
# The indention of each line controls whether it is within a loop, if statement, etc. -- there
are no { } to define blocks of code. This use of indentation in Python is unusual, but it's
logical and you get used to it.
####################################################
## 4. Functions
####################################################
x=1
y=2
x, y = swap(x, y) # => x = 2, y = 1
# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x=5
def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print(x) # => 43
def set_global_x(num):
global x
print(x) # => 5
x = num # global var x is now set to 6
print(x) # => 6
set_x(43)
set_global_x(6)
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
####################################################
## 5. Modules
####################################################
Example:
#!/usr/bin/python -tt
"""
-tt flag above detects space/tab indent problems
"""
def main():
# [Link] contains command line arguments.
# This assigns a list of all but the first arg into a local 'args' var.
args = [Link][1:]
Exercises:
Additional exercises
Page 31 of 100
Lab No:4
Lab No :4 Date:
An object is simply a collection of data (variables) and methods (functions) that act on
those data. Similarly, a class is a blueprint for that object.
We can think of class as a sketch (prototype) of a house. It contains all the details about
the floors, doors, windows etc. Based on these descriptions we build the house. House is
the object.
As many houses can be made from a house's blueprint, we can create many objects from
a class. An object is also called an instance of a class and the process of creating this
object is called instantiation.
Page 32 of 100
Lab No:4
Like function definitions begin with the def keyword in Python, class definitions begin
with a class keyword.
The first string inside the class is called docstring and has a brief description about the
class. Although not mandatory, this is highly recommended.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined. Attributes
may be data or functions.
There are also special attributes in it that begins with double underscores __. For
example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This
class object allows us to access the different attributes as well as to instantiate new
objects of that class.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print([Link])
Output
10
<function [Link] at 0x7fc78c6e8160>
This is a person class
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
This will create a new object instance named harry. We can access the attributes of
objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of
that class.
Page 34 of 100
Lab No:4
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
Output
You may have noticed the self parameter in function definition inside the class but we
called the method simply as [Link]() without any arguments. It still worked.
This is because, whenever an object calls its method, the object itself is passed as the
first argument. So, [Link]() translates into [Link](harry).
Page 35 of 100
Lab No:4
For these reasons, the first argument of the function in class must be the object itself.
This is conventionally called self. It can be named otherwise but highly recommend to
follow the convention.
Another Example:
class Human:
# Note that the double leading and trailing underscores denote objects
# __repr__ etc. are called special methods (or sometimes called dunder methods)
[Link] = name
Page 36 of 100
Lab No:4
# Initialize property
self._age = 0
def sing(self):
# They are called with the calling class as the first argument
@classmethod
def get_species(cls):
return [Link]
@staticmethod
def grunt():
return "*grunt*"
Page 37 of 100
Lab No:4
# It turns the method age() into an read-only attribute of the same name.
@property
def age(self):
return self._age
@[Link]
self._age = age
@[Link]
def age(self):
del self._age
# When a Python interpreter reads a source file it executes all its code.
# This __name__ check makes sure this code block is only executed when this
if __name__ == '__main__':
# Instantiate a class
Page 38 of 100
Lab No:4
i = Human(name="Ian")
j = Human("Joel")
# i and j are instances of type Human, or in other words: they are Human objects
[Link] = 42
Page 39 of 100
Lab No:4
del [Link]
class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))
Exercises:
Page 40 of 100
Lab No:4
1. Write a Python class to get all possible unique subsets from a set of distinct
integers
Input:[4,5,6]
Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]
2. Write a Python class to find a pair of elements (indices of the two numbers) from
a given array whose sum equals a specific target number.
Input: numbers= [10,20,10,40,50,60,70], target=50
Output: 3, 4
3. Write a Python class to implement pow(x, n).
4. Write a Python class which has two methods get_String and print_String.
get_String accept a string from the user and print_String print the string in upper
case.
Additional Exercises:
1. Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' and
']. These brackets must be close in the correct order, for example "()" and "()[]{}"
are valid but "[)", "({[)]" and "{{{" are invalid.
2. Write a Python class to reverse a string word by word.
3. Write a Python class named Circle constructed by a radius and two methods which
will compute the area and the perimeter of a circle.
Page 41 of 100
Lab No:5
Myproject is the name of the project created. The following list of files are created inside
the directory.
[Link] – It is a command-line utility that allows to interact with the Django project
in various ways.
myproject/ – It is the actual Python package for the project. It is used to import anything,
say – [Link].
Page 42 of 100
Lab No:5
[Link] – Init just tells the python that this is to be treated like a python package.
Now to create the application, type the below command in Powershell from the created
project folder (i.e., myproject).
Now the ‘webapp’ directory will have some extra things from the original myproject. It
includes model, test which are related to the backend databases.
It is important to import your application manually inside the project settings. For that,
open myproject/[Link] and add your app manually:
INSTALLED_APPS = (
'webapp',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
)
Now to create a view, open webapp/[Link] and put the below code in it:
The above code creates a view which returns HttpResponse. Now this view is to be
mapped to a URL. So create a new python file “[Link]” inside the webapp folder. In
webapp/[Link] include the following code:
In the above code, a view is referenced which will return index (defined in [Link] file).
The url pattern is in regular expression format where ^ stands for beginning of the string
and $ stands for the end.
The next step is to point the root URLconf at the [Link] module. Open
myproject/[Link] file and write the below code:
In the above code, webapp and the [Link] are included. Now import
[Link] and insert an include() in the urlpatterns list. The include()
function allows referencing other URLconfs.
Note that the regular expression doesn’t have a ‘$’ but rather a trailing slash, this means
whenever Django encounters include(), it chops off whatever part of the URL matched
up to that point and sends the remaining string to include URLconf for further processing.
Page 44 of 100
Lab No:5
Fig 5.1
2. Creating a View
Django’s views are the information brokers of a Django application. A view sources
data from your database (or an external data source or service) and delivers it to a
template. The view makes decisions on what data gets delivered to the template—either
by acting on input from the user, or in response to other business logic and internal
processes. Each Django view performs a specific function and has an associated template.
# \webapp\[Link]
4 import calendar
Page 45 of 100
Lab No:5
8 def index(request,year,month):
9 year = int(year)
10 month = int(month)
12 month_name = calendar.month_name[month]
# \webapp\[Link]
4 urlpatterns = [
6 re_path(r'^(?P<year>[0-9]{4})/(?P<month>0?[1-9]|1[0-2])/', [Link],
name='index'),
7]
Page 46 of 100
Lab No:5
Fig 5.2
All modern websites have a site template; a common look or branding that is duplicated
across every page on the website.
The most common place for storing site template files in Django is in the website app that
Django created automatically when startproject command is executed. Django didn’t
create the templates folder, so go ahead and create that folder. The folder structure should
look like this:
\webapp
\templates
__init__.py
...
As the website app is not in INSTALLED_APPS, Django won’t automatically look for
templates in the \webapp\templates folder. So tell Django where to look by adding a path
to the DIRS setting. Modify [Link] (changes in bold):
TEMPLATES = [{
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR, 'webapp/templates')],
Page 47 of 100
Lab No:5
'APP_DIRS': True,
# ...
This looks complicated, but is easy to understand—[Link] is a Python command to
create a file path by joining strings together (concatenating). In this example,
webapp/templates is joined to the project directory to create the full path to the templates
directory, i.e., <project path>/myproject/webapp/templates.
Now that the template folder is created and the folder path is listed, Django can find the
site template. Now to create a simple template, create a html file [Link]:
# \webapp\templates\[Link]
1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>Basic Site Template</title>
6 </head>
7
8 <body>
9 <h1>{{ title }}</h1>
10 <p>{{ cal }}</p>
11 </body>
12 </html>
3. Displaying a Template
Now that the template is created, tell Django to use the new base template when
displaying content on the site. This is done in [Link] file. Make the following changes
to the index view (changes in bold):
# \webapp\[Link]
9 year = int(year)
10 month = int(month)
11 if year < 1900 or year > 2099: year = [Link]().year
12 month_name = calendar.month_name[month]
13 title = "MyClub Event Calendar - %s %s" % (month_name, year)
14 cal = HTMLCalendar().formatmonth(year, month)
15 # return HttpResponse("<h1>%s</h1><p>%s</p>" % (title, cal))
16 return render(request, '[Link]', {'title': title, 'cal': cal})
For the new view, replace the call to HttpResponse() with a call to render(). render() is a special
Django helper function that creates a shortcut for communicating with a web browser. When
Django receives a request from a browser, it finds the right view and the view returns a response
to the browser.
When we wish to use a template, Django first must load the template, create a context—which is
basically a dictionary of variables and associated data that is passed back to the browser—and
then return a HttpResponse. Django’s render() function provides a shortcut that provides all
three steps in a single function.
When the original request, the template and a context is supplied directly to render(), it returns
the appropriately formatted response without having to code the intermediate steps.
In the modified [Link], the original request object is returned from the browser, the name of
the site template and a dictionary (the context) containing the title and cal variables from the view.
Once [Link] file is modified, save it and fire up the development server. Navigate to
[Link] to see your simple new site template.
The calendar will be rendered as plain text, not as HTML. To get Django to render the HTML
correctly, turn off autoescape for the calendar code. As this is a common task, the Django
developers created the autoescape tag to make life easier. Make the following changes to
the [Link] file (changes in bold):
# \webapp\templates\[Link]
1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>Basic Site Template</title>
Page 49 of 100
Lab No:5
6 </head>
7
8 <body>
9 <h1>{{ title }}</h1>
10 <p>{% autoescape off %}{{ cal }} {% endautoescape %}</p>
11 </body>
12 </html>
Now, when you refresh your browser, the site homepage should look like Fig 5.3.
Fig 5.3
Solved Excersise:
Develop a simple Django web application to accept two numbers from user and add
them up.
A new project named MyForm is created which has the [Link] file. Inside MyForm
a new app named formapp is created which contains all the application related files.
# MyForm/[Link]
INSTALLED_APPS = [
'formapp',
'[Link]',
'[Link]',
]
TEMPLATES = [
Page 50 of 100
Lab No:5
{
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR,'formapp/templates')],
'APP_DIRS': True,
},
]
# MyForm/[Link]
from [Link] import admin
from [Link] import path
from [Link] import include, url
urlpatterns = [
path(r'^admin/', [Link]),
url('', include('[Link]')),
]
# formapp/[Link]
from [Link] import url
from . import views
urlpatterns = [
url(' ', [Link], name='index'),
]
# formapp/[Link]
from [Link] import render
# Create your views here.
def index(request):
return render(request, '[Link]')
# formapp/templates/[Link]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
Page 51 of 100
Lab No:5
</head>
<body>
<script type="text/javascript">
function myfunc(){
var n1= [Link]("num1").value;
var n2= [Link]("num2").value;
var n3=parseInt(n1)+parseInt(n2);
[Link]("para1").innerHTML="The sum of two numbers is
"+n3;
}
</script>
Enter num1: <input type="text" id="num1"><br>
Enter num2: <input type="text" id="num2"><br>
<button onclick="myfunc()">Add</button><br\>
<p id="para1"></p>
</body>
</html>
After editing all the above files save them and fire up the development server as shown
below
E:\newdir\MyForm> python [Link] runserver
Navigate to [Link] and find the output as shown in Fig 5.4.
Fig 5.4
LAB EXERCISES:
1) Create a web form which allows the teacher to enter the student details like name,
date of birth, address, contact number, email id and marks of English, Physics and
Chemistry. After filling all the information and on clicking submit button, details
Page 52 of 100
Lab No:5
should be added to a textarea displayed on the same page. Display the total
percentage of marks obtained in a label.
2) Create a web form with employee ids in dropdown list. Use a textbox for accepting
date of joining. Add a button named “Am I Eligible for Promotion”. On clicking
the button, if he has more than 5 years of experience, then display “YES” else
“NO” in the label control.
3) Develop a simple web page to perform basic arithmetic operations. Take two
integer inputs from the user, select the operation to be performed using a
dropdown. Include a button “Calculate” to perform the selected operation, and
then display the result in the same web page.
4) Develop a simple web form that generates the front cover for a magazine. The
form should provide the options for selecting the image, background color,
changing font size, color etc. Input messages must be taken from the user so as to
display it on the front cover with legible font family and font size. The front cover
developed should be proportionate to the web page size. Place the css files inside
static folder.
ADDITIONAL EXERCISES:
1) Develop a simple web page to reproduce the given Captcha. Upon match, suitable
message has to be displayed. If there is a mismatch for more than 3 times, TextBox
has to be disabled.
2) Design a simple web application to provide information about a book. The home
page of the application should display the cover page of the book along with three
hyperlinks: Metadata, Reviews, Publisher info. Give provision to revert to home
page from any other page.
Page 53 of 100
Lab No:6
Django Forms:
When one creates a Form class, the most important part is defining the fields of the form.
Each field has custom validation logic. Forms are basically used for taking input from the
user in some manner and using that information for logical operations on databases. For
example, registering a user by taking input as his name, email, password, etc.
Django maps the fields defined in Django forms into HTML input fields. Django handles
three distinct parts of the work involved in forms:
• preparing and restructuring data to make it ready for rendering
• creating HTML forms for the data
• receiving and processing submitted forms and data from the client
Syntax:
Django Fields have the following syntax:
field_name = [Link](**options)
The forms library comes with a set of Field classes that represent common validation
needs.
For each field, we describe the default widget used. We also specify the value returned
when you provide an empty value.
Page 54 of 100
Lab No:6
BooleanField
class BooleanField(**kwargs)
CharField
class CharField(**kwargs)
ChoiceField
class ChoiceField(**kwargs)
DateField
class DateField(**kwargs)
Page 55 of 100
Lab No:6
EmailField
class EmailField(**kwargs)
FileField
class FileField(**kwargs)
IntegerField
class IntegerField(**kwargs)
• max_value
• min_value
URLField
class URLField(**kwargs)
Page 56 of 100
Lab No:6
FIELD
DESCRIPTION
OPTIONS
By default, each Field class assumes the value is required, so to make it not
The label argument lets you specify the “human-friendly” label for this field.
The label_suffix argument lets you override the form’s label_suffix on a per-
The widget argument lets you specify a Widget class to use when rendering
The help_text argument lets you specify descriptive text for this Field. If you
provide help_text, it will be displayed next to the Field when the Field is
The error_messages argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
Page 57 of 100
Lab No:6
FIELD
DESCRIPTION
OPTIONS
The validators argument lets you provide a list of validation functions for this
validators field.
The localize argument enables the localization of form data input, as well as
The disabled boolean argument, when set to True, disables a form field using
• max_length
• min_length
Core Field arguments are the arguments given to each field for applying some constraint
or imparting a particular characteristic to a particular Field. For example, adding an
argument required = False to CharField will enable it to be left blank by the user.
Page 58 of 100
Lab No:6
To use Django Forms, create a project and an app inside it. After you start an app, create
a form in app/[Link].
For creating a form in Django we have to specify what fields would exist in the form and
of what type.
# app/[Link]
class RegForm([Link]):
title = [Link]()
description = [Link]()
views = [Link]()
available = [Link]()
Django form fields have several built-in methods to ease the work of the developer but
sometimes one needs to implement things manually for customizing User Interface(UI).
A form comes with 3 in-built methods that can be used to render Django form fields.
• {{ form.as_table }} will render them as table cells wrapped in <tr> tags
• {{ form.as_p }} will render them wrapped in <p> tags
• {{ form.as_ul }} will render them wrapped in <li> tags
# app/[Link]
from [Link] import render
from .forms import RegForm
# creating a home view
def home_view(request):
context = {}
Page 59 of 100
Lab No:6
#app/ templates/[Link]
<html>
<body>
<form action="" method="POST">
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
Use the command ‘python [Link] runserver’ to see the following output in the web
page (Fig 6.1):
Fig 6.1
Page 60 of 100
Lab No:6
A widget is Django’s representation of an HTML input element. The widget handles the
rendering of the HTML, and the extraction of data from a GET/POST dictionary that
corresponds to the widget.
Whenever you specify a field on a form, Django will use a default widget that is
appropriate to the type of data that is to be displayed.
However, if you want to use a different widget for a field, you can use
the widget argument on the field definition. For example:
class CommentForm([Link]):
name = [Link]()
url = [Link]()
comment = [Link](widget=[Link])
This would specify a form with a comment that uses a larger Textarea widget, rather than
the default TextInput widget.
These widgets make use of the HTML elements input and textarea.
TextInput
class TextInput
• input_type: 'text'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="text" ...>
NumberInput
class NumberInput
• input_type: 'number'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="number" ...>
Page 61 of 100
Lab No:6
EmailInput
class EmailInput¶
• input_type: 'email'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="email" ...>
PasswordInput
class PasswordInput
• input_type: 'password'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="password" ...>
HiddenInput
class HiddenInput
• input_type: 'hidden'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="hidden" ...>
DateInput
class DateInput
• input_type: 'text'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="text" ...>
Textarea
class Textarea
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <textarea>...</textarea>
Page 62 of 100
Lab No:6
CheckboxInput
class CheckboxInput
• input_type: 'checkbox'
• template_name: 'django/forms/widgets/[Link]'
• Renders as: <input type="checkbox" ...>
Select
class Select
• template_name: 'django/forms/widgets/[Link]'
• option_template_name: 'django/forms/widgets/select_option.html'
• Renders as: <select><option ...>...</select>
Sample code:
RadioSelect
class RadioSelect
• template_name: 'django/forms/widgets/[Link]'
• option_template_name: 'django/forms/widgets/radio_option.html'
Similar to Select, but rendered as a list of radio buttons within <li> tags:
<ul>
<li><input type="radio" name="..."></li>
</ul>
Sample Code:
YES_SMARTPHONE = 'Yes'
NO_SMARTPHONE = 'No'
SMART_PHONE_OWNERSHIP = ((YES_SMARTPHONE, 'Yes'),
(NO_SMARTPHONE, 'No'),)
Page 63 of 100
Lab No:6
smart_phone_ownership=[Link](widget=[Link](),
choices=SMART_PHONE_OWNERSHIP, initial= "", label='Do you own a
Smartphone?', required = False)
We can override the default widget of each field for various purposes. To do so we need
to explicitly define the widget we want to assign to a field.
Make following changes to app/[Link]
class GeeksForm([Link]):
title = [Link](widget = [Link])
description = [Link](widget = [Link])
views = [Link](widget = [Link])
available = [Link](widget = [Link])
Fig 6.2
Page 64 of 100
Lab No:6
Solved Exercise:
#loginapp/ [Link]
#loginapp/[Link]
else:
MyLoginForm = LoginForm()
#loginapp/templates/[Link]
<html>
<body>
<br>
<br>
</center>
</div>
</form>
</body>
</html>
#loginapp/templates/[Link]
<html>
<body>
You are : <strong>{{username}}</strong>
Your number is : <strong>{{contact_num}}</strong>
</body>
</html>
Page 66 of 100
Lab No:6
Fig 6.3
Django Sessions:
Sessions are used to abstract the receiving and sending of cookies, data is saved on server
side (like in database), and the client side cookie just has a session ID for identification.
Sessions are also useful to avoid cases where the user browser is set to ‘not accept’ cookie
Setting Up Sessions
In Django, enabling session is done in your project [Link], by adding some lines to
the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should
be done while creating the project, so MIDDLEWARE_CLASSES should have −
'[Link]'
And INSTALLED_APPS should have −
'[Link]'
By default, Django saves session information in database (django_session table or
collection), but we can configure the engine to store information using other ways like:
in file or in cache.
Page 67 of 100
Lab No:6
When session is enabled, every request (first argument of any view in Django) has a
session (dict) attribute.
Solved Exercise:
#sessapp/[Link]
#Sessapp/[Link]
def formView(request):
if [Link].has_key('username'):
username = [Link]['username']
return render(request, '[Link]', {"username" : username})
else:
return render(request, '[Link]', { })
def logout(request):
try:
del [Link]['username']
except:
pass
return HttpResponse("<strong>You are logged out.</strong>")
Page 68 of 100
Lab No:6
#sessapp/templates/[Link]
<html>
<body>
<br>
<br>
</center>
</div>
</form>
</body>
</html>
Page 69 of 100
Lab No:6
#sessapp/templates/[Link]
<html>
<body>
You are : <strong>{{username}}</strong>
</body>
</html>
#sessapp/[Link]
urlpatterns = [
url(r'^connection/',[Link], name = 'formView'),
url(r'^login/', [Link], name = 'login'),
url(r'^logout/', [Link], name = 'logout'),
]
Commands to be used:
Page 70 of 100
Lab No:6
Fig 6.4
LAB EXERCISES:
ADDITIONAL EXERCISES:
1) Develop a Web Application for Grocery Checklist Generation as shown in the figure
below. It must have checkboxes which must be populated on page load listing grocery
items. On clicking the Add Item button the selected Items and their prices have to be
displayed in a Table. Set the borderstyle and border width for the table and its cells.
Page 71 of 100
Lab No:6
2) Create a website with two pages. Page 1 has two TextBoxes (name and total marks) and
one ‘Calculate’ Button as shown in the figure. On clicking the ‘Calculate’ Button, CGPA
(total marks/50) along with the name should be displayed in the Page 2. Use Django
sessions to store the information.
Page 72 of 100
Lab No:7
Mini-project-phase-I
Objectives:
Page 73 of 100
Lab No:8
Databases
Objectives:
1. MySql
2. PostgreSql
3. Oracle
4. Sqllite
With the help of 3rd party backend Django supports following databases
Solved Exercise
Model is the name given to data abstraction part. To create the model you must first
create an app. To create an app right click on the project→Add→DjangoApp
Page 74 of 100
Lab No:8
Step1: In [Link] add the app name (blog) under Installed_Apps as follows:
INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'blog'
TEMPLATES = [
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR,'blog/templates/blog')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'[Link].context_processors.debug',
'[Link].context_processors.request',
'[Link].context_processors.auth',
Page 75 of 100
Lab No:8
'[Link].context_processors.messages',
],
},
},
If you are using sqllite leave the default setting for database which will look as
follows
DATABASES = {
'default': {
'ENGINE': '[Link].sqlite3',
If you are using MySQL in that case modify the database entry as follows
DATABASES = {
'default': {
'ENGINE':'[Link]',
Page 76 of 100
Lab No:8
# [Link]
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8
[Link]()
urlpatterns = [
# Examples:
#url(r'^MyBlog/', include('[Link]')),
# url(r'^admin/doc/', include('[Link]')),
Page 77 of 100
Lab No:8
# (r'^$', '[Link].redirect_to',
# {'url': '/blog/'}),
url(r'^blog/', include('[Link]')),
url(r'^admin/', include([Link])),
Step3: Under blog app create a file named [Link] and type the following
urlpatterns = [
Page 78 of 100
Lab No:8
class BlogPost([Link]):
title = [Link](max_length=150)
body = [Link]()
timestamp = [Link]()
class Meta:
ordering = ('-timestamp',)
class BlogPostForm([Link]):
class Meta:
model = BlogPost
exclude = ('timestamp',)
It contains the details of table and Model form uses the model already created to create
the form. This approach avoids duplication of code and goes with python philosophy
Do not Repeat Yourself.
Step5: Registering your app in the admin: To register your app type the following into
[Link]
import site
class BlogPostAdmin([Link]):
[Link]([Link],BlogPostAdmin)
Page 79 of 100
Lab No:8
def archive(request):
posts = [Link]()[:10]
def create_blogpost(request):
if [Link] == 'POST':
form = BlogPostForm([Link])
if form.is_valid():
post = [Link](commit=False)
[Link]=[Link]()
[Link]()
return HttpResponseRedirect('/blog/')
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<input type=submit>
</form>
<hr>
<hr>
{% endfor %}
</body>
</html>
This is the template which displays the blog posts that are separated by horizontal rule.
i. Go to Projects→Django Check
If it succeeds then
Once you have created the superuser you can open the website. It looks as follows
append /admin to the host name you will get the following screen
Page 82 of 100
Lab No:8
Type the superuser name and password you will be taken to following admin page. In
the admin page you can see entry for Blog Posts as you have registered it.
Page 83 of 100
Lab No:8
Add a blog post You will be taken to following screen you can observe only title and
timestamp are visible as per our code
Page 84 of 100
Lab No:8
Now you append the blog to the address you will get the following output.
Page 85 of 100
Lab No:8
As per our instructions users cannot edit the timestamp and current date and time will be
taken for user entry. The blog entered by admin is also displayed. Once you enter the
blog post details it will display it as under.
Page 86 of 100
Lab No:8
Page 87 of 100
Lab No:8
Lab Excercises
1. Design a web site using Django, which is a website directory – A site containing
links to other websites. A web page has different categories.
• A category table has a name, number of visits, and number of likes.
• A page table refers to a category, has a title, URL, and many views.
Design a form that populates the above database and displays it.
3. There are three tables in the database an author table has a first name, a last
name and an email address. A publisher table has a name, a street address, a city,
a state/ province, a country, and a Web site. A book table has a title and a
publication date. It also has one or more authors (a many-to-many relationship
with authors) and a single publisher (a one-to-many relationship - aka foreign
key - to publishers). Design a form which populates and retrieves the
information from the above database using Django.
4. Create a Django Page for entry of a Product information (title, price and
description) and save it into the db. Create the index page where you would view
the product entries in an unordered list.
Additional Exercises
1. Create a web page with DropDownList, Textboxes and Buttons. Assume the
table ‘Human’ with First name, Last name, Phone, Address and City as fields.
Page 88 of 100
Lab No:8
When the page is loaded, only first names will be displayed in the drop-down
list. On selecting the name, other details will be displayed in the respective
TextBoxes. On clicking the update button, the table will be updated with new
entries made in the text box. On clicking the delete button, the selected record
will be deleted from the table, and the DropDownList is refreshed.
2. Assume a table “Institutes” with institute_id, name, and no_of_courses are the
fields. Create a web page that retrieves all the data from “Institutes” table
displays only Institute names in the list box.
Page 89 of 100
Lab No:9
Mini-project-Phase-II
Objectives:
At the end of Phase-II of mini-project student must implement database concept into the
mini-project and assign different roles and responsibilities to different users.
Administration of website must be possible.
Page 90 of 100
Lab No:10
ReST API
Objectives:
I. DESCRIPTION
REST is acronym for REpresentational State Transfer. It is architectural style for
distributed hypermedia systems and was first presented by Roy Fielding in 2000.
User owns a website and has all the code and database connections already set up and it
is working fine. Now, he/she decides to develop a mobile application for his/her website.
In such a case, it becomes extremely difficult and time-consuming to configure the same
database connections separately around different mobile OSs. Instead of that, the user can
build a REST API on top of the current WEB application and use that API to serve
requests from the mobile application irrespective of the devices. As ReST API returns a
JSON, which is a common format and not specific to any devices. So, it becomes easy
for various devices to communicate with each other. Another key feature of REST API is
that if the user has an API to perform certain operations then he/she does not have to
rewrite that as part of the code and thereby it also reduces the size of the code.
Page 91 of 100
Lab No:10
The key abstraction of information in REST is a resource. Any information that can be
named can be a resource: a document or image, a temporal service, a collection of other
resources, a non-virtual object (e.g. a person), and so on. REST uses a resource identifier
to identify the resource involved in an interaction between components.
Resources are represented by URIs. The clients send requests to these URIs using the
methods defined by the HTTP protocol, and possibly because of that the state of the
affected resource changes.
HTTP
Action Examples
Method
Obtain information [Link]
GET
about a resource (retrieve student list)
Obtain information [Link]
GET
about a resource (retrieve student #123)
[Link]
POST Create a new resource (create a new student, from data provided with the
request)
Page 92 of 100
Lab No:10
[Link]
PUT Update a resource (update student #123, from data provided with the
request)
[Link]
DELETE Delete a resource
(delete student #123)
HTTP Methods
• A layered system that organizes each type of server (those responsible for
security, load-balancing, etc.) involved the retrieval of requested information
into hierarchies, invisible to the client.
• Code-on-demand (optional): the ability to send executable code from the server
to the client when requested, extending client functionality.
The starting point in selection of resources is to analyze your business domain and extract
the nouns that are relevant to your business needs. More importantly, focus should be
given to the needs of API consumers and how to make the API relevant and useful from
the perspective of API consumer interactions. Once the nouns (resources) have been
identified, then the interactions with the API can be modeled as HTTP verbs against these
nouns. When they don't map nicely, we could approximate. For example, we can easily
use the “nouns in the domain” approach and identify low level resources such as Post,
Tag, Comment, etc. in a blogging domain. Similarly, we can identify the nouns Customer,
Address, Account, Teller, etc. as resources in a banking domain.
To create a project we should move to the directory where we would like to store our
code. For this go to command line and use cd command. Then trigger the startproject
command.
django-admin startproject pollsapi
For database setup, go to pollsapi/[Link] and make sure it contains the following
entry
DATABASES = {
'default': {
'ENGINE': '[Link].sqlite3',
Page 94 of 100
Lab No:10
For creating the polls api we are going to create a Poll model, a Choice model, and a
Vote model. Once we are done with designing our models, the [Link] file should
look like this:
class Choice([Link]):
poll = [Link](Poll, related_name='choices',
on_delete=[Link])
choice_text = [Link](max_length=100)
def __str__(self):
return self.choice_text
class Vote([Link]):
choice = [Link](Choice, related_name='votes',
on_delete=[Link])
poll = [Link](Poll, on_delete=[Link])
voted_by = [Link](User, on_delete=[Link])
class Meta:
unique_together = ("poll", "voted_by")
To create the database tables to our models, ‘rest_framework’ and ‘polls’ app needs to
be added to the “INSTALLED_APPS” in the ‘django_pollsapi/settings’ file.
INSTALLED_APPS = (
Page 95 of 100
Lab No:10
...
'rest_framework',
'polls',
)
Run the makemigrations command which will notify Django that new models have
been created and those changes needs to be applied to the migration. Run migrate
command to do the actual migration.
python [Link] makemigrations polls
python [Link] migrate
return JsonResponse(data)
def polls_detail(request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = {"results": {
"question": [Link],
"created_by": poll.created_by.username,
"pub_date": poll.pub_date
}}
return JsonResponse(data)
The API can be tested using Postman using the following url and GET method:
[Link]
2. Create a ReST service for Ola Cabs with the requirement given below:
The service should provide the following real time information about Ola rides available
at a given user location (latitude and longitude).
• Estimated time of arrival (ETA)
• Fare details
Implement the CRUD operations for the resources identified and create a client to
consume the service.
3. Design and implement a ReST service for Romato, which gives you access to the
freshest and most exhaustive information for over 1 million restaurants across 1,000 cities
globally. With the Romato APIs, one can search for restaurants by name, cuisine, or
location. Identify any three resources and implement CRUD operations.
4. Design a ReST service for RodeSprinter, which is a one-stop solution for all local
needs. Through the API, the website can request for any amenity from Fish, meat,
groceries, vegetables, flowers, cakes, hotel food, home cooked food, medicines, bill
payments, documents pickup and so much more. Basically, anything from anywhere.
With the RodeSprinter APIs, one can search for amenities by name, or location. Identify
any three Resources and implement CRUD operations.
Page 97 of 100
Lab No:10
ADDITIONAL EXERCISES:
1. Design a ReST service for an e-learning platform such as Coursera. Identify any three
resources and implement CRUD operations.
2. Design a ReST service for bus ticket booking site. Identify any three resources and
implement CRUD operations.
Page 98 of 100
Lab No : 11&12
Mini Project
Objective:
1. Demonstrate the website developed as part of the mini project along with report and
presentation.
Project Details
1. Abstract
2. Motivation
3. Objectives
4. Introduction
5. Literature review
6. Methodology
7. Results
8. Limitations and Possible Improvements
9. Conclusion
10. References
Other type of projects can exclude literature review.
Page 99 of 100
References:
3. Leif Azzopardi and David Maxwell, Tango with Django 2, Apress, 2019