ITLAB 2024 AIML Eval
ITLAB 2024 AIML Eval
CERTIFICATE
LAB [CSE XXXX] of Third Year B. Tech. (Computer Science and Engineering-Artificial
Intelligence and Machine Learning) Degree at MIT, Manipal, in the academic year 2023-
2024.
Date: ……...................................
Signature
Faculty in Charge
CONTENTS
Evaluation plan i
1 HTML5 1–7
3 Javascript 13 – 31
4 JQuery 32 – 41
8 74 – 89
Form Processing using Django – Part I
9 90 – 90
Form Processing using Django – Part II
10 Databases – Part I 90 – 98
12 Mini-project-Phase-1 102-102
13 References 103
Course Objectives
• Acquire in-depth understanding of web application architecture.
• Understand techniques to improve user experience in web applications.
• Gain knowledge about how to interact with database.
Course Outcomes
At the end of this course, students will be able to
Evaluation plan
• Internal Assessment Marks : 60%
i
INSTRUCTIONS TO THE STUDENTS
Pre- Lab Session Instructions
1. Students should carry the Lab Manual Book and the required stationery to every
lab session
2. Be in time and follow the institution dress code
3. Must Sign in the log register provided
4. Make sure to occupy the allotted seat and answer the attendance
5. Adhere to the rules and maintain the decorum
6. Students must come prepared for the lab in advance
ii
• Questions for lab tests and examination are not necessarily limited to the questions
in the manual, but may involve some variations and / or combinations of the
questions.
• A sample note preparation is given as a model for observation.
iii
Lab No:2
DESCRIPTION
HTML5 – Hyper Text Markup Language Version 5
HTML5 is the 5th and newest version of HTML standard, providing new features
like rich media support, interactive web applications etc.
The most interesting HTML5 elements are:
• Semantic elements like <header>, <footer>, <article> and <section>
• Attributes of form elements like number, date, time, calendar and
range.
• Graphic elements like <svg> and <canvas>
Page 4 of 100
Lab No:2
</head>
<body>
<h1> Hello </h1>
<h2> Welcome to Internet Technologies Lab </h2>
</body>
</html>
HTML5 Elements
HTML5 offers new elements for better document structure. The below given table
gives a brief description on few HTML5 elements.
TAG DESCRIPTION
<article> Defines an article in a document
<dialog> Defines a dialog box or window
<header> Defines a header for a document or a section
Page 5 of 100
Lab No:2
Tag Description
<a> Defines a hyperlink
<br> Produces a single line break
<div> Specifies a division or a section in a document
<h1> to Defines a HTML headings
<h6>
<hr> Produces a horizontal lines
<span> Defines a inline styleless section in a document
<nav> Defines a navigation links
HTML5 Events
On visiting a website the user perform actions like clicking on links or image, hover
over things etc. These are considered to be examples for Events.
Page 6 of 100
Lab No:2
Event handlers are developed to handle these events and this can be done using a
scripting language like JavaScript, VBScript etc wherein event handlers are
specified as a value of event tag attribute.
The following attributes (very few) can be used to trigger any javascript or vbscript
code given as value, when there is any event occurs for any HTM5 element.
HTML5 Canvas
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. The user must use JavaScript
to actually draw the graphics. Canvas has several methods for drawing paths, boxes,
circles, text, and adding images.
Page 7 of 100
Lab No:2
Note: Always specify an Id attribute (to be referred to in a script), and a width and
height attribute to define the size of the canvas. To add a border, use the style
attribute.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid
#d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas> <script> var c =
document.getElementById("myCanvas");
var ctx = c.getContext("2d"); ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>
Output
Page 8 of 100
Lab No:2
Figure 1.4
Page 9 of 100
Lab No:2
Method attribute
The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data.
<form action = “/action_page.aspx” method=”get”>
The default method when submitting form data is GET. When GET is used
the submitted form data will be visible in the page address field. Therefore it must
not be used when sending sensitive information.
Use POST method if the form data contains sensitive or personal
information. It does not display the submitted form data in the page address field. It
has no size limitations and can be used to send large amounts of data.
II. LAB EXERCISE:
1. Write a simple poem and represent it as a web page. Give a title for the poem.
Make rhyming words in the poem as bold.
2. Assume you have brought a new car. Write down the list of additional
accessories you need for the car as an unordered list in HTML. Also, list the
travel plans on the car as an ordered list.
3. Complete the following website name “Share your Winter Vacation Videos”.
The required video files are located inside the compressed folder “Week 1
Assignment Files/Media/”.
Hint: Add a <video> element to a <figure> element that will either play
paris.mp4, paris.webm or paris.ogv in the element. Test in different browsers
Page 10 of 100
Lab No:2
Page 11 of 100
Lab No:2
<head>
<link rel=”stylesheet” href = “style.css”>
</head>
style.css
h1 { color : blue ;}
The style definitions are usually saved in an external stylesheet since changing
one single file can help in redesigning the entire web document with new look
and feel.
Page 12 of 100
Lab No:2
CSS syntax
A CSS rule set consists of a selector and a declaration block. The selector points
to the HTML element to be styled. The declaration block contains one or more
declarations separated by semicolons
CSS Selectors are used to “find” or select HTML elements based on their element
name, id, class, attribute etc. The element selector selects the elements based on
the element name. The id selector uses the id attribute of an HTML element to
select a specific element. The id of an element should be unique within a page. To
select an element with a specific id, write a # character followed by the id of the
element.
#para1{
text-align: center;
color:red; }
The class selector selects the elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by
the name of the class.
.center {
text-align: center;
color:red;
}
Page 13 of 100
Lab No:2
Bootstrap
• 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)
• Example:
<!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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></scr
ipt>
</head>
<body>
<div class="container">
<h1>My First Bootstrap Page</h1>
<p>This part is inside a .container class.</p>
<p>The .container class provides a responsive fixed width container.</p>
<p>Resize the browser window to see that its width (max-width) will change at
different breakpoints.</p>
</div>
</body>
</html>
Page 14 of 100
Lab No:2
Lab Exercise:
1. Design the student bio-data form using button, label, textbox, radio button, table and
checkbox using CSS.
2. Design a web page which shows the database oriented CRUD operation. Consider
Employee data using CSS.
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
different input groups, input, badges, buttons and button groups. Make the design more
attractive using bootstrap.
Additional Exercise:
Page 15 of 100
Lab No : 3 Date:
JavaScript
Objectives:
In this lab, student will be able to
Syntax
It can be implemented using JavaScript statements that are placed within the
<script>….</script> HTML tags in a web page. The <script> tags, containing the
JavaScript code can be placed anywhere within the web page, but normally
recommended to place within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as script. The script tag have mainly two attributes language and
type, specifying the scripting language used.
Page 16 of 100
<script language=”javascript” type=”text/javascript”>
</script>
Program:
Login.html
<!DOCTYPE html>
<html>
<head>
<title> Login page </title>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
</style>
<script language="javascript">
function check(form) /*function to check userid & password*/
{
Page 17 of 100
/*the following code checkes whether the entered userid and password are
matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.open("https://www.google.com", "_blank");
/*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username") /*displays error message*/
}
}
</script>
</head>
<body>
<h1> Validate Credentials </h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</body>
</html>
Page 18 of 100
LAB EXERCISE:
3) Write the java script program to display the grade [A, B,C,D] based on the marks
entered by student(take the input into text boxes). Enter the marks of 4 subjects and
calculate the average( using button). If the avg>90 then A, avg>80 then B, if avg>70
then C, if avg>60 then D.
ADDITIONAL QUESTIONS
1) Write a JavaScript code that displays text “FONT+++” with increasing font size
in the interval of 200ms in RED COLOR, when the font size reaches 40pt it
displays “FONT---” in BLUE color. Then the font size decreases to 5pt.
2) Write a JavaScript to design a simple calculator to perform the following
operations: sum, product, difference and quotient.
Page 19 of 100
Lab No : 4 Date:
JQuery
Objectives:
In this lab, student will be able to
jQuery
jQuery is a fast and concise JavaScript library to develop web based application.
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>
Page 21 of 100
<div>
<p class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
We can select tag available with the given class in the DOM. For example $('.someclass')
selects all elements in the document that have a class name as some-class.
You can replace a complete DOM element with the specified HTML or DOM elements.
selector.replaceWith( content )
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
$(this).replaceWith("<h1>JQuery is Great</h1>");
});
});
</script>
Page 22 of 100
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
The hover( over, out ) method simulates hovering (moving the mouse on, and off,
an object).
checked selector selects all checked check-boxes or radio buttons. Let us understand
this with an example.
<html>
<head>
<title></title>
<script src="jquery-1.11.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#divResult').html(result.val() + " 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>
Page 24 of 100
<head>
<title></title>
<script src="jquery-1.11.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('#divResult').html(resultString);
} 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.
3. Create a web page to design a birthday card shown below.
Page 26 of 100
4. Design a webpage. The page contains:
• Dropdown list with HP, Nokia, Samsung, Motorola, Apple as items.
• Checkbox with Mobile and Laptop as items. Textbox where you enter quantity.
• There is a button with text as ‘Produce Bill’.
On Clicking Produce Bill button, alert should be displayed with total amount.
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.
Lab No:2
Page 27 of 100
Lab No:5 Date:
Myproject is the name of the project created. The following list of files are created inside
the directory.
manage.py – It is a command-line utility that allows to interact with the Django project
in various ways.
Page 28 of 100
myproject/ – It is the actual Python package for the project. It is used to import anything,
say – myproject.urls.
Lab No:5
init.py – Init just tells the python that this is to be treated like a python package.
settings.py – This file manages all the settings of the project. urls.py – This is
the main controller which maps it to the website. wsgi.py – It serves as an entry
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/settings.py and add your app manually:
INSTALLED_APPS = (
'webapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
Now to create a view, open webapp/views.py and put the below code in it:
Page 29 of 100
return HttpResponse("<H2>HEY! Welcome to Edureka! </H2>")
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 “urls.py” inside the webapp folder. In
webapp/urls.py include the following code:
In the above code, a view is referenced which will return index (defined in views.py 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 webapp.urls module. Open
myproject/urls.py file and write the below code:
In the above code, webapp and the webapp.urls are included. Now import
django.conf.urls.include 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 30 of 100
E:\MyFolder\myproject> python manage.py runserver
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\views.py
4 import calendar
Page 32 of 100
7
8 def index(request,year,month):
9 year = int(year)
10 month = int(month)
12 month_name = calendar.month_name[month]
# \webapp\urls.py
4 urlpatterns = [
6 re_path(r'^(?P<year>[0-9]{4})/(?P<month>0?[1-9]|1[0-2])/', views.index,
name='index'),
7 ]
Page 33 of 100
Lab No:5
Lab No:5
Fig 5.2
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 settings.py (changes in bold):
Page 34 of 100
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'webapp/templates')],
'APP_DIRS': True,
# ...
This looks complicated, but is easy to understand—os.path.join 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 base.html:
# \webapp\templates\base.html
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 views.py file. Make the following changes to the index
view (changes in bold):
# \webapp\views.py
Page 35 of 100
Lab No:5
1 from django.shortcuts import render
2 # from django.http import HttpResponse
3 from datetime import date
4 import calendar
5 from calendar import HTMLCalendar
6
7
8 def index(request, year=date.today().year, month=date.today().month):
Page 36 of 100
Lab No:5
9 year = int(year)
10 month = int(month)
11 if year < 1900 or year > 2099: year = date.today().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, 'base.html', {'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 views.py, 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 views.py file is modified, save it and fire up the development server. Navigate to
http://127.0.0.1:8000/, 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
base.html file (changes in bold):
# \webapp\templates\base.html
1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
Page 37 of 100
Lab No:5
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 manage.py file. Inside MyForm
a new app named formapp is created which contains all the application related files.
# MyForm/settings.py
INSTALLED_APPS = [
'formapp',
'django.contrib.admin',
'django.contrib.auth',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
Page 38 of 100
Lab No:5
'DIRS': [os.path.join(BASE_DIR,'formapp/templates')],
'APP_DIRS': True,
},
]
# MyForm/urls.py from
django.contrib import admin from
django.urls import path
from django.conf.urls import include, url
urlpatterns = [ path(r'^admin/',
admin.site.urls),
url('', include('formapp.urls')),
]
# formapp/urls.py from
django.conf.urls import url from
. import views
urlpatterns = [
url(' ', views.index, name='index'),
]
# formapp/views.py from
django.shortcuts import render #
Create your views here.
def index(request):
return render(request, 'basic.html')
# formapp/templates/basic.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
Page 39 of 100
Lab No:5
</head>
<body>
<script type="text/javascript"> function
myfunc(){ var n1=
document.getElementById("num1").value; var n2=
document.getElementById("num2").value;
var n3=parseInt(n1)+parseInt(n2);
document.getElementById("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 manage.py runserver
Navigate to http://127.0.0.1:8000/, and find the output as shown in Fig 5.4.
Fig 5.4
Page 40 of 100
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
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.
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.
Page 41 of 100
Lab No:6
Lab No:6 Date:
1) 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.
2) 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) Design a simple web application which will ask the user to input his name and a
message, display the two items concatenated in a label, and change the format of
the label using radio buttons and check boxes for selection, the user can make the
label text bold, underlined or italic and change its color. include buttons to display
the message in the label, clear the text boxes and label and exit
Page 42 of 100
Lab No:7 Date:
Mini-project-phase-I
Objectives:
Page 43 of 100
Lab No:6
1. Identify an idea to implement a mini project using ASP.NET concepts.
2. Formulate the synopsis for a mini project.
3. Perform the requirement gathering and design phases of the project.
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 = forms.FieldType(**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.
BooleanField class
BooleanField(**kwargs)
Page 45 of 100
Lab No:6
CharField class
CharField(**kwargs)
ChoiceField class
ChoiceField(**kwargs)
DateField class
DateField(**kwargs)
Page 46 of 100
FileField class
FileField(**kwargs)
IntegerField class
IntegerField(**kwargs)
• max_value
• min_value
URLField class
URLField(**kwargs)
Page 47 of 100
Lab No:6
FIELD
OPTIONS DESCRIPTION Lab No:6
By default, each Field class assumes the value is required, so to make it not
required you need to set required=False
required
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 this
Field. See Widgets for more information.
widget
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
rendered by one of the convenience Form methods.
help_text
Page 48 of 100
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
want to override.
error_messages
Page 49 of 100
Lab No:6
The validators argument lets you provide a list of validation functions for this
field.
validators
The localize argument enables the localization of form data input, as well as the
rendered output.
localize
The disabled boolean argument, when set to True, disables a form field using
the disabled HTML attribute so that it won’t be editable by users.
disabled.
• 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.
To use Django Forms, create a project and an app inside it. After you start an app, create
a form in app/forms.py.
Page 50 of 100
Lab No:6
For creating a form in Django we have to specify what fields would exist in the form and of
what type.
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/views.py from
django.shortcuts import render
from .forms import RegForm #
creating a home view def
home_view(request):
context = {} form =
RegForm(request.POST or None)
context['form'] = form return
render(request, "home.html", context)
Page 51 of 100
Lab No:6
#app/ templates/home.html
<html>
<body>
<form action="" method="POST">
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
Use the command ‘python manage.py runserver’ to see the following output in the web page
(Fig 6.1):
Fig 6.1
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.
Page 52 of 100
Lab No:6
However, if you want to use a different widget for a field, you can use the widget argument
on the field definition. For example:
from django import forms class
CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget=forms.Textarea)
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/text.html'
• Renders as: <input type="text" ...>
NumberInput class
NumberInput
• input_type: 'number'
• template_name: 'django/forms/widgets/number.html'
• Renders as: <input type="number" ...>
EmailInput class
EmailInput¶
• input_type: 'email'
• template_name: 'django/forms/widgets/email.html'
Page 53 of 100
Lab No:6
• input_type: 'password'
• template_name: 'django/forms/widgets/password.html'
• Renders as: <input type="password" ...>
HiddenInput class
HiddenInput
• input_type: 'hidden'
• template_name: 'django/forms/widgets/hidden.html'
• Renders as: <input type="hidden" ...>
DateInput class
DateInput
• input_type: 'text'
• template_name: 'django/forms/widgets/date.html'
• Renders as: <input type="text" ...>
Textarea class
Textarea
• template_name: 'django/forms/widgets/textarea.html'
• Renders as: <textarea>...</textarea>
CheckboxInput class
CheckboxInput
• input_type: 'checkbox'
• template_name: 'django/forms/widgets/checkbox.html'
• Renders as: <input type="checkbox" ...>
Page 54 of 100
Lab No:6
Select class
Select
• template_name: 'django/forms/widgets/select.html'
• option_template_name: 'django/forms/widgets/select_option.html'
Renders as: <select><option ...>...</select>
Sample code:
forms.ChoiceField(widget=forms.Select, choices=CHOICES)
RadioSelect class
RadioSelect
• template_name: 'django/forms/widgets/radio.html'
• 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'),)
smart_phone_ownership=forms.ChoiceField(widget=forms.RadioSelect(),
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/forms.py
Page 55 of 100
Lab No:6
class GeeksForm(forms.Form):
title = forms.CharField(widget = forms.Textarea)
description = forms.CharField(widget = forms.CheckboxInput)
views = forms.IntegerField(widget = forms.TextInput)
available = forms.BooleanField(widget = forms.Textarea) The
output obtained will be as follows (Fig 6.2):
Fig 6.2
Solved Exercise:
A Sample program to demonstrate passage of multiple parameters from one page to another.
#loginapp/ forms.py
Page 56 of 100
Lab No:6
#loginapp/views.py
else:
MyLoginForm = LoginForm()
#loginapp/templates/login.html
<html>
<body>
Page 57 of 100
<br>
<br>
</center>
</div>
</form>
</body>
</html>
#loginapp/templates/loggedin.html
<html>
<body>
You are : <strong>{{username}}</strong>
Your number is : <strong>{{contact_num}}</strong>
</body> </html>
Page 58 of 100
Command to be used: E:\MyFolder\FormProject > python manage.py runserver
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 settings.py, 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 −
'django.contrib.sessions.middleware.SessionMiddleware'
And INSTALLED_APPS should have −
'django.contrib.sessions'
Page 59 of 100
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.
When session is enabled, every request (first argument of any view in Django) has a
session (dict) attribute.
Lab No:6
#Sessapp/views.py
def formView(request): if
request.session.has_key('username'):
username = request.session['username']
return render(request, 'loggedin.html', {"username" : username})
else:
return render(request, 'login.html', { })
def logout(request):
try:
del request.session['username']
except: pass
return HttpResponse("<strong>You are logged out.</strong>")
Page 60 of 100
#sessapp/templates/login.html
Lab No:6
<html>
<body>
<br>
<br>
</form>
</body>
</html>
#sessapp/templates/loggedin.html
Page 62 of 100
Lab No:6
<html>
<body>
You are : <strong>{{username}}</strong>
</body>
</html> #sessapp/urls.py
urlpatterns = [
url(r'^connection/',views.formView, name = 'formView'),
url(r'^login/', views.login, name = 'login'),
url(r'^logout/', views.logout, name = 'logout'),
]
Commands to be used:
E:\MyFolder\SessProject> python manage.py migrate
Fig 6.4
Page 63 of 100
Lab No:6
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 64 of 100
Lab No:6
LAB QUESTIONS
1) Create a Register page and Success page with the following requirements:
i. Register page should contain four input TextBoxes for UserName, Password,
Email id and Contact Number and also a button to submit. Make the username as
compulsory field and other fields as optional.
ii. On button click, Success page is displayed with message "Welcome
{UserName}" and also his Email and Contact Number has to be displayed.
iii. Use secure technique to send details to the Success page (Hint: use csrftoken) 4)
Design a website with two pages.
2) “How is the book ASP.NET with c# by Vipul Prakashan?” Give the user three choice : i) Good
ii) Satisfactory iii) Bad. Provide a VOTE button. After user votes, present the result in
percentage using labels next to the choices
3) 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 65 of 100
ADDITIONAL QUESTIONS
2)Write a program to display the following feedback form. The different options for
the list box must be ASP-XML, DotNET, JavaPro and Unix,C,C++. When the Submit
Form button is clicked after entering the data, a message as seen in the last line of
the above figure must be displayed.
Page 66 of 100
Lab No:8
Lab No:10 Date:
Databases – Part I
Objectives:
1. MySql
2. PostgreSql
3. Oracle
4. Sqllite
With the help of 3rd party backend Django supports following databases
Page 67 of 100
Lab No:8
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
Let us name the app as “blog”
Step1: In settings.py add the app name (blog) under Installed_Apps as follows:
INSTALLED_APPS = [
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
]
Under Templates provide the path of the template directory as follows
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'blog/templates/blog')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Page 68 of 100
Lab No:8
If you are using sqllite leave the default setting for database which will look as
follows
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
If you are using MySQL in that case modify the database entry as follows
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql',
'OPTIONS': {' read_default_file': '/path/to/my.cnf',},
}
}
# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8
Page 69 of 100
Lab No:8
Step2: Modify the Projects urls.py as given below from
urlpatterns = [
# Examples:
# url(r'^$', MyBlog.views.archive, name='archive'),
#url(r'^MyBlog/', include('MyBlog.MyBlog.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
include('blog.urls')), url(r'^admin/',
include(admin.site.urls)),
Step3: Under blog app create a file named urls.py and type the following
archive,create_blogpost
Page 70 of 100
Lab No:8
Step4: Under models.py type the following from
BlogPost(models.Model):
title
models.CharField(max_length=
150) body =
models.TextField()
timestamp =
models.DateTimeField()
class Meta:
ordering = ('-timestamp',)
class BlogPostForm(forms.ModelForm):
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
admin.py from django.contrib import admin import site from blog.models import
BlogPost
Page 71 of 100
Lab No:8
# Register your models here. from blog
BlogPostAdmin(admin.ModelAdmin):
admin.site.register(models.BlogPost,BlogPostAdmin)
BlogPostForm
def archive(request):
posts = BlogPost.objects.all()[:10]
def create_blogpost(request):
if request.method == 'POST':
form = BlogPostForm(request.POST)
if form.is_valid():
Page 72 of 100
Lab No:8
post = form.save(commit=False)
post.timestamp=datetime.now()
post.save()
return HttpResponseRedirect('/blog/')
<head>
<title></title>
</head>
<body>
<input type=submit>
</form>
<hr>
Page 73 of 100
Lab No:8
<hr>
{% endfor %}
</body> </html>
This is the template which displays the blog posts that are separated by horizontal rule.
Page 74 of 100
Lab No:8
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 75 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 76 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 77 of 100
Lab No:8
Now you append the blog to the address you will get the following output.
Page 78 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 79 of 100
Lab No:8
Page 80 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.
ADDITIONAL EXERCISES
1. 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 81 of 100
Lab No:11 Date:
Databases-Part II
Lab Exercise
1. 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.
2. 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.
3. Create a web page with DropDownList, Textboxes and Buttons. Assume the
table ‘Human’ with First name, Last name, Phone, Address and City as fields.
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.
ADDITIONAL QUESTIONS
1. Create a web page that receives the following information from a set of students: Student
Id, Student Name, Course Name and Date of Birth. The application should also display the
information of all the students once the data is Entered.
Page 82 of 100
Lab No:12 Date:
Mini-project-Phase-II
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 83 of 100
References:
3. Leif Azzopardi and David Maxwell, Tango with Django 2, Apress, 2019
Page 84