You are on page 1of 456

Django

What is Django?
1) Django is a Python-based free and open-source web framework. It is used to develop efficient
websites in short time with less code.
2) So, Django makes it easier to build better web apps more quickly and with less code.
3) official website of Django is: www.djangoproject.com
4) Django is Freeware (no need to pay single paisa) and opensource (we can customize according our
requirements)
5) Django framework is completely written in python
6) Django is maintained by DSF (Django Software Foundation)

What is a Framework?
Ans: Framework is a software which provides generic functionality for application. (OR) It is a platform
for developing software applications. It includes code libraries, a compiler, and other related programs.

What is Web Application Framework?


Ans: It is a software Framework that is designed to support the development of web applications
including web services, web resources, and web APIs.

When Django is invented and who invented?


Ans: 2003 by Adrian Holovaty, Simon Willison and it is named after famous guitarist Django Reinhardt.
(Note: In google, just type: django is invented in)

What is the latest version of Django?


Ans: 3.1.4
(Just open www.djangoproject.com here we can see all latest updates of Django Framework)

Which companies are using Django?


2093 companies reportedly use Django in their tech stacks, including Pinterest, Instagram, and Udemy.

 Pinterest
 Instagram
 Udemy
 Robinhood
 Delivery Hero
 Bepro Company
 Coursera
 Accenture

What are famous web applications which are developed by using Django:

(just type in google: top 10 django apps)


(and also just type in google: 25 of the most popular python and Django websites)
The following technologies to be learned to become master in Django:
1) Core python
2) Advanced python
3) Databases
4) Core HTML
5) Advanced HTML
6) Core CSS
7) Advanced CSS
8) Core Java Script
9) Advanced Java Script
10) Core Django concepts
11) Advanced Django concepts
12) Django projects

1) HTML5

What is HTML?

 HTML stands for Hyper Text Markup Language


 HTML is for creating Web pages

A Simple HTML Document


 Open notepad

 Type HTML code

 Save the file as webpage1.html on your desktop

The following is the HTML code:


File name: webpage1.html

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>Django Framework</h1>
<p>Django is a Web Framework. It is used to develop websites with less effort</p>

</body>
</html>

The following image will be appeared on desktop. Double click on this icon.

Output:
Note: In the above example, except <h1> tag and <p> tag, remaining tags are optional.

Example Explained

 The <!DOCTYPE html> declaration defines that this document is an HTML5 document
 The <html> element is the root element of an HTML page
 The <head> element contains information about the HTML page
 The <title> element specifies a title for the HTML page (which is shown in the browser's title bar
or in the page's tab)
 The <body> element defines the document's body, and is a container for all the visible contents,
such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
 The <h1> element defines a large heading
 The <p> element defines a paragraph

Note: In body tag, “bgcolor” property can be used. With this webpage background color will be set.

Ex:

<body bgcolor=pink>

Note: with the above line, “pink” background will be set to the webpage. We can also use quotations for
the color name as follows:

<body bgcolor="pink">

Note: background colors are : red, green, blue, yellow, pink, white, black, purple, orange, grey etc..

Note: Heading tags are from <h1> to <h6>

File: HeadingTags.html

Code:
<! -- These are heading tags -- >

<h1>Django Framework</h1>

<h2>Django Framework</h2>

<h3>Django Framework</h3>

<h4>Django Framework</h4>

<h5>Django Framework</h5>

<h6>Django Framework</h6>

Output:

Note: Comments will not be appeared on the web page. Comments are used to describe the program.

Note: In HTML, comments are placed with <! -- type comment -- >

 we can use style property in all heading tags along with this we can also use <b> <i> tags as follows:

<b><i><h1 style=color:blue> Django framework </h1>

Note: <b> tag for Bold letters and <i> tag for italic letters.

Output:
In paragraph tag, we can use the following properties:

<p style=text-align:right;color:green;font-size:30px> Django paragraph1</p>

<p style=text-align:left;color:red;font-size:40px> Django paragraph2</p>

<p style=text-align:center;color:blue;font-size:50px> Django paragraph1</p>

Output:
Note: default alignment is left

<marquee> tag:

It is used to move the text.

Note: by default, with <marquee> tag, text will be moved to left side.

Ex:

File: Marquee1.html

Requirement: Scroll “Welcome to learn Django” text, and body background colour is blue

<body bgcolor=blue>

<h1>

<marquee> Welcome to learn Django </marquee>

File: Marquee2.html

Requirement: Scrolling text2 will be with 100pixels font size, with blue color and moving to left side and
with yellow colour body background.

<body bgcolor=yellow>

<marquee><p style=font-size:100px;color:blue> Welcome to learn Django </p></marquee>

File: Marquee3.html
Requirement: Scrolling text3 with green color marquee background and scrolled to left side and with
orange body background color

<body bgcolor=orange>

<h1>

<marquee bgcolor=green> Welcome to learn Django </marquee>

File: Marquee4.html

Requirement: Scrolling text4 will be scrolled to up side, marquee background colour is yellow and body
background colour is green.

<body bgcolor=green>

<h1>

<marquee bgcolor=yellow direction=up> Welcome to learn Django </marquee>

File: Marquee5.html

Requirement: Scrolling text5 will be scrolled to up side, marquee background colour is yellow and marquee
height is 20%, and body background colour is pink.

<body bgcolor=pink>

<h1>

<marquee bgcolor=yellow direction=up height=20%> Welcome to learn Django </marquee>

File: Marquee6.html

Requirement: marquee background colour is yellow, direction is down, height is 50%, width is 50% and
body background colour is blue.

<body bgcolor=blue>

<h1>

<marquee bgcolor=yellow direction=down height=50% width=50%> Welcome to learn Django </marquee>

File: Marquee7.html

Requirement: body background colour is blue, marquee background colour is yellow, direction is down,
height is 50%, width is 50% and text should scrolled in center.

<body bgcolor=blue>
<h1>

<marquee bgcolor=yellow direction=down height=50% width=50%><center> Welcome to learn Django


</center></marquee>

File: Marquee8.html

Requirement: Body background colour is blue, marquee background colour is yellow, direction is right side,
font size is 100 pixels.

<body bgcolor=blue>

<marquee bgcolor=yellow direction=right style=font-size:100px>Django</marquee>

File: Marquee9.html

Requirement: Body background colour is blue, marquee background colour is yellow, scrolling speed is 40
and font size is 100 pixels.

<body bgcolor=blue>

<marquee bgcolor=yellow scrollamount=40 style=font-size:100px>Welcome to learn Django</marquee>

Note: any +ve number can be given to scrollamount

<a> - anchor tag:

The <a> tag defines a hyperlink, which is used to link from one page to another.

Ex:

File: AnchorTag.html

<body bgcolor=pink>
<h1>
<a href="http://www.rnreddyitschool.co/">Click here to go to RN Reddy IT School website</a>
<br>
<a href="https://www.python.org/">Click here to go to Python website</a>
<br>
<a href="https://www.djangoproject.com/">Click here to go to Django Website</a>
<img> tag

The <img> tag is used to embed an image in an HTML page.

Ex:

File: ImageTag1.html

<img src="C:\Users\USER\Downloads\benzcar1.jpg">

<img src="C:\Users\USER\Downloads\benzcar1.jpg">

<img src="C:\Users\USER\Downloads\benzcar1.jpg">

<img src="C:\Users\USER\Downloads\benzcar1.jpg">

Output:
File: ImageTag2.html

<img src="C:\Users\USER\Downloads\benzcar1.jpg" height=500 width=500>

Output:
<table> tag:

The <table> tag defines an HTML table.

An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.

The <tr> element defines a table row, the <th> element defines a table header, and the <td> element
defines a table cell.

Ex:

File: table1.html

<body bgcolor=green>

<center>

<img src="C:\Users\USER\Downloads\collegeimage1.jpg">

<h1 style=color:yellow><u> Student Details Table </u></h1>

<table border=True width=70%>

<tr bgcolor=blue>

<th style=font-size:25px;color:yellow>Student ID</th>

<th style=font-size:25px;color:yellow>Student Name</th>

<th style=font-size:25px;color:yellow>Student Address</th>

<th style=font-size:25px;color:yellow>Student Mobile Number</th>

<th style=font-size:25px;color:yellow>Student Course</th>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 101 </td>

<td style=font-size:20px><b> Raju </td>

<td style=font-size:20px><b> Hyd </td>

<td style=font-size:20px><b> 9988776655 </td>

<td style=font-size:20px><b> Django </td>

</tr>
<tr bgcolor=orange>

<td style=font-size:20px><b> 102 </td>

<td style=font-size:20px><b> Ravi </td>

<td style=font-size:20px><b> Chennai </td>

<td style=font-size:20px><b> 9977665544 </td>

<td style=font-size:20px><b> Django </td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 103 </td>

<td style=font-size:20px><b> Ramesh </td>

<td style=font-size:20px><b> Banglore </td>

<td style=font-size:20px><b> 9999887766 </td>

<td style=font-size:20px><b> Django </td>

</tr>

</table>

Output:
Ex:

File: table2.html

<body bgcolor=green>

<center>

<img src="D:\collegeimage1.jpg">

<h1 style=color:yellow><u> Student Details Table </u></h1>

<table border=True width=70%>

<tr bgcolor=blue>

<th style=font-size:25px;color:yellow>Student ID</th>

<th style=font-size:25px;color:yellow>Student Name</th>

<th style=font-size:25px;color:yellow>Student Address</th>

<th style=font-size:25px;color:yellow>Student Mobile Number</th>

<th style=font-size:25px;color:yellow>Student Course</th>

<th style=font-size:25px;color:yellow>Student image</th>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 101 </td>

<td style=font-size:20px><b> Pooja </td>

<td style=font-size:20px><b> Hyd </td>

<td style=font-size:20px><b> 9988776655 </td>

<td style=font-size:20px><b> Django </td>

<td><img src="D:\studentimage1.jpg" height=200 width=200></td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 102 </td>

<td style=font-size:20px><b> Ravi </td>


<td style=font-size:20px><b> Chennai </td>

<td style=font-size:20px><b> 9977665544 </td>

<td style=font-size:20px><b> Django </td>

<td><img src="D:\studentimage2.jpg" height=200 width=200></td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 103 </td>

<td style=font-size:20px><b> Ramesh </td>

<td style=font-size:20px><b> Banglore </td>

<td style=font-size:20px><b> 9999887766 </td>

<td style=font-size:20px><b> Django </td>

<td><img src="D:\studentimage3.jpg" height=200 width=200></td>

</tr>

</table>

Output
Ex:

File: table3.html

<body bgcolor=black>

<center>

<img src="D:\benzcar1.jpg" height=500 width=1050>

<h1 style=color:yellow><u> Mercedes Benz cars</u></h1>

<table border=True width=70%>

<tr bgcolor=blue>

<th style=font-size:25px;color:yellow>Car Model</th>

<th style=font-size:25px;color:yellow>Car Video</th>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> Mercedes S Class Cabriolet Roof-35 MPH Open Close Mercedes CARJAM
TV HD 2016 </td>

<td style=font-size:20px><b><a
href="https://www.youtube.com/watch?v=idgwm3kv3R0">Demo</a></td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 2020 BRABUS 700 Mercedes-AMG GT 63 S </td>

<td style=font-size:20px><b><a
href="https://www.youtube.com/watch?v=o_hHTUceflw">Demo</a></td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px><b> 2020 Mercedes-Benz GLE 400d 4MATIC Coupe </td>

<td style=font-size:20px><b><a
href="https://www.youtube.com/watch?v=7UETinXc1_g">Demo</a></td>

</tr>

</table>
Output:

Note: Car videos will be played once “Demo” link is clicked.

HTML Lists

HTML lists allow web developers to group a set of related items in lists.

Example:

An unordered HTML list: An ordered HTML list:

 Item 1. First item


 Item 2. Second item
 Item 3. Third item
 Item 4. Fourth item

Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

The list items will be marked with bullets (small black circles) by default:

Example

<ul>
<li>Milk</li>
<li>Tea</li>
<li>Coffee</li>
</ul>
File: unorderedlist1.html

<body bgcolor=pink>
<ul>
<li>Notebook</li>
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ul>

Output:

File Name: unorderedlist2.html

<body bgcolor=yellow>

<h1>

<ul>

<li style=color:blue>Milk</li><img src="D:\milk.jpg" height=200 width=200><br><br>

<li style=color:green>Tea</li><img src="D:\tea.jpg" height=200 width=200><br><br>

<li style=color:red>Coffee</li><img src="D:\coffee.jpg" height=200 width=200><br><br>

</ul>
Output:

File: nested_unordered_list.html

<body bgcolor=black>

<h1>

<ul>

<li style=color:blue>Python

<ul>

<li>Core Python</li>

<li>Advance Python</li>

</ul>

</li>

<br>

<li style=color:green>HTML

<ul>

<li>Core HTML</li>

<li>Advanced HTML</li>
</ul>

</li>

<br>

<li style=color:purple>CSS

<ul>

<li>Core CSS</li>

<li>Advanced CSS</li>

</ul>

</li>

<br>

<li style=color:orange>Java Script

<ul>

<li>Core Java Script</li>

<li>Advanced Java Script</li>

</ul>

</li>

<br>

<li style=color:red>Django

<ul>

<li>Core Django</li>

<li>Advanced Django</li>

</ul>

</li>

</ul>

Output:
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items will be marked with numbers by default:

Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

File: orderedlist1.html

<body bgcolor=pink>

<ol style=color:blue>

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ol>

Output:
File: orderedlist2.html

<body bgcolor=yellow>

<h1>

<ol>

<li style=color:blue>HP laptop i7 model</li><img src="D:\hplaptop1.jpg"><img


src="D:\hplaptop2.jpg"><img src="D:\hplaptop3.jpg"><img src="D:\hplaptop4.jpg"><br><br>

<li style=color:green>Dell i7 laptop</li><img src="D:\delllaptop1.jpg"><img


src="D:\delllaptop2.jpg"><img src="D:\delllaptop3.jpg"><img src="D:\delllaptop4.jpg"><br><br>

<li style=color:red>Lenovo i7 laptop</li><img src="D:\lenovolaptop1.jpg"><img


src="D:\lenovolaptop2.jpg"><img src="D:\lenovolaptop3.jpg"><img src="D:\lenovolaptop4.jpg"><br><br>

</ol>

</h1>

</body>

Output:
<video> tag

<video> tag is used to add a video to web page.

Ex:

<video width=500 controls>

<source src="D:\HP Spectre x360 13 HP.mp4">

</video>

File: videos1.html

<body bgcolor=yellow>

<video width=600 controls>

<source src="D:\Dell G3 15 Laptop Product Video (2019).mp4">

</video>

<video width=600 controls>

<source src="D:\HP Spectre x360 13 HP.mp4">

</video>

<video width=600 controls>

<source src="D:\Tested! Lenovo IdeaPad S540 Laptop Review.mp4">


</video>

<video width=600 controls>

<source src="D:\HP 15 BS013 CORE i7 7th GENERATION LAPTOP.mp4">

</video>

Output:

File: videos2.html

<body bgcolor=green>

<center>

<h2 style=color:yellow> HP Spectre x360 13

<br>

<video width=500 controls>

<source src="D:\HP Spectre x360 13 HP.mp4">

</video>

<br><br><br>
Lenovo IdeaPad S540

<br>

<video width=500 controls>

<source src="D:\Tested! Lenovo IdeaPad S540 Laptop Review.mp4">

</video>

Output

File: videos3.html

<body bgcolor=blue>

<center>

<h1 style=color:yellow><u> Laptop videos</u></h1>

<table border=True>

<tr bgcolor=green>

<th style=font-size:25px;color:yellow>Laptop Model</th>

<th style=font-size:25px;color:yellow> Video</th>


</tr>

<tr bgcolor=orange>

<td style=font-size:20px;color:blue><b> Dell G3 15 Laptop

<br>

<ul style=color:green>

<li> Core i5 9th Gen</li>

<li>8GB/512GB</li>

<li>Windows 10 Home</li>

<li>4 GB Graphics</li>

<li>1 TB HDD</li>

<li>Rs.69,990</li>

</ul>

</td>

<td>

<video width=600 controls>

<source src="D:\Dell G3 15 Laptop Product Video (2019).mp4">

</video>

</td>

</tr>

<tr bgcolor=orange>

<td style=font-size:20px;color:blue><b> HP Spectre x360 13

<br>

<ul style=color:green>

<li> Core i5 10th Gen</li>


<li>8GB/512GB SSD</li>

<li>Windows 10 Pro</li>

<li>8 GB Graphics</li>

<li>2 TB HDD</li>

<li>Rs.1,28,990</li>

</ul>

</td>

<td>

<video width=600 controls>

<source src="D:\HP Spectre x360 13 HP.mp4">

</video>

</td>

</tr>

</table>

Output:
The <form> Element
The HTML <form> element is used to create an HTML form for user input

Ex:

<form>
.
form elements
.
</form>

The <form> element is a container for different types of input elements, such as: text
fields, checkboxes, radio buttons, submit buttons, etc.

The <input> Element


The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on the type attribute.

Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field or simply called as Text
field.

<input type="radio"> Displays a radio button (for selecting one of many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)

<input type="button"> Displays a clickable button

Note: default type of <input> element is “text”.

File: form1.html
<body bgcolor=blue>

<h1 style=color:orange><u> Customer Details Form </u></h1>

<form>

<h2 style=color:yellow>

First name

<input type="text" ><br><br>

Last name

<input type="text"><br><br>

Gender:<br>

<input type="radio" name="gender"> Male <br>

<input type="radio" name="gender"> Female

<br><br>

Age

<input type="text"><br><br>

Mobile Number

<input type="text"><br><br>

Address

<input type="text"><br><br>

Hobbies:<br>

<input type="checkbox">Reading<br>

<input type="checkbox">Playing<br>
<input type="checkbox">Singing<br>

<input type="checkbox">Dancing<br>

<br><br>

<input type="button" value="Submit" style="height:40px; width:100px; font-


size:20px; color:blue"><br><br>

</form>

Output:

 Let us develop the following form:


File: sampleform1.html

<body bgcolor=pink>

<b>

<form>

Name

<input type="text" name="customer_name" required><br><br>

Phone

<input type="tel" name="phone_number" required><br><br>

Email
<input type="email" name="email_address" required><br><br>

<fieldset>

<legend> Which taxi do you require? </legend>

<input type="radio" name="taxi" required value="car"> Car <br><br>

<input type="radio" name="taxi" required value="van"> Van <br><br>

<input type="radio" name="taxi" required value="truck"> Truck

</fieldset>

<br><br>

<fieldset>

<legend>Extras</legend>

<input type="checkbox" name="extras" value="baby"> Baby Seat <br><br>

<input type="checkbox" name="extras" value="wheelchair"> Wheelchair Access <br><br>

<input type="checkbox" name="extras" value="tip"> Stock Tip <br><br>

</fieldset>

<br><br>

Pickup Date/Time

<input type="datetime-local" name="pickup_time" required><br><br>

Pickup Place

<select id="pickup_place" name="pickup_place">


<option value="" selected="selected">Select One</option>

<option value="office" >Taxi Office</option>

<option value="town_hall" >Town Hall</option>

<option value="telepathy" >At your place</option>

</select>

<br><br>

Dropoff Place

<input type="text" name="dropoff_place" required list="destinations"><br><br>

<datalist id="destinations">

<option value="Airport">

<option value="Beach">

<option value="Fred Flinstone's House">

</datalist>

<br>

Special Instructions

<textarea name="comments" maxlength="500"></textarea>

<br><br>

<button>Submit Booking</button>

</form>

File: Form2.html
In this Form2.html, whenever user clicks on “Submit” button then customer details will
be displayed in the same web page.

<html>

<head>

<script>

function display()

document.getElementById("p1").innerHTML = "First Name is:


"+document.getElementById("fname").value;

document.getElementById("p2").innerHTML = "Last Name is


:"+document.getElementById("lname").value;

document.getElementById("p3").innerHTML = "Gender is:


"+document.querySelector('input[name="gender"]:checked').value;

document.getElementById("p4").innerHTML = "Age is:


"+document.getElementById("age").value;

document.getElementById("p5").innerHTML = "Mobile Number is:


"+document.getElementById("mobilenumber").value;

document.getElementById("p6").innerHTML = "Address is:


"+document.getElementById("address").value;

document.getElementById("p7").innerHTML = "Hobby1 is:


"+document.querySelector('input[name="hobby1"]:checked').value;

document.getElementById("p8").innerHTML = "Hobby2 is:


"+document.querySelector('input[name="hobby2"]:checked').value;

document.getElementById("p9").innerHTML = "Hobby3 is:


"+document.querySelector('input[name="hobby3"]:checked').value;

document.getElementById("p10").innerHTML = "Hobby4 is:


"+document.querySelector('input[name="hobby4"]:checked').value;

</script>

</head>

<body bgcolor=blue>
<img src="D:\c1.jpg" height=400 widht=400><br>

<h1 style=color:orange><u> Customer Details Form </u></h1>

<form>

<h2 style=color:yellow>

First name

<input type="text" id="fname"><br><br>

Last name

<input type="text" id="lname"><br><br>

Gender:<br>

<input type="radio" name="gender" value="Male"> Male <br>

<input type="radio" name="gender" value="Female"> Female

<br><br>

Age

<input type="text" id="age"><br><br>

Mobile Number

<input type="text" id="mobilenumber"><br><br>

Address

<input type="text" id="address"><br><br>

Hobbies:<br>

<input type="checkbox" name="hobby1" value="Reading">Reading<br>


<input type="checkbox" name="hobby2" value="Playing">Playing<br>

<input type="checkbox" name="hobby3" value="Singing">Singing<br>

<input type="checkbox" name="hobby4" value="Dancing">Dancing<br>

<br><br>

<input type="button" value="Submit" style="height:40px; width:100px; font-


size:20px; color:blue" onClick="display()"><br><br>

<br><br>

<p id="p1"></p><br>

<p id="p2"></p><br>

<p id="p3"></p><br>

<p id="p4"></p><br>

<p id="p5"></p><br>

<p id="p6"></p><br>

<p id="p7"></p>

<p id="p8"></p>

<p id="p9"></p>

<p id="p10"></p>

</form>

Note: we can also specify <script> tag as follows:

<script type = "text/javascript">

Output:

Enter the data and press “submit” button.


Cascading Style Sheet (CSS)

CSS is used to control the style of a web document in a simple and easy way.
CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,
CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to
advanced concepts.

Why to Learn CSS?


Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. The following are the key
advantages of learning CSS:
 Create Stunning Web site - CSS handles the look and feel part of a web page. Using
CSS, you can control the color of the text, the style of fonts, the spacing between
paragraphs, how columns are sized and laid out, what background images or colors are
used, layout designs, variations in display for different devices and screen sizes as well as
a variety of other effects.
 CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages
as you want.
 Pages load faster - If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag.
So less code means faster download times.
 Easy maintenance - To make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
 Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you
can give a far better look to your HTML page in comparison to HTML attributes.
 Multiple Device Compatibility - Style sheets allow content to be optimized for more than
one type of device. By using the same HTML document, different versions of a website can
be presented for handheld devices such as PDAs and cell phones or for printing.
 Global web standards - Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
 Control web - CSS is easy to learn and understand but it provides powerful control over
the presentation of an HTML document. Most commonly, CSS is combined with the
markup language HTML.
 Become a web designer - If you want to start a career as a professional web designer,
HTML and CSS designing is a must skill.

Hello world program in CSS:

File: helloworld.html

<html>

<head>

<title>This is document title</title>

<style>

h1 {

color: #36CFFF;

</style>

</head>

<body>

<h1>Hello World!</h1>

</body>
</html>

Note:

<style>

h1 {

color: #36CFFF;

</style>

is CSS code.

Output:

Generally, when <h1> tag is used, then the following is the output:

Code:

<h1> welcome </h1>


Now we can give special styles to <h1> tag by using CSS as follows:

File: cssfile1.html

<style>

h1 {

color: blue;

background-color: yellow;

font-size: 180px;

letter-spacing: 90px;

text-transform: uppercase;

</style>

<h1> welcome </h1>

Output:
Note: The code between <style> and </style> tags is CSS code.

Note: text-transform can be “lowercase” also.

Note:

Inline CSS code: Outline CSS code:

<h1 style=color:blue;background-color:yellow;font- <style>


size:120px;letter-spacing:90px;text-
transform:uppercase>heading 1</h1> h1 {

Note: Whatever the styles we used for <h1> tag color: blue;
then those styles are applicable to one <h1> tag
only. background-color: yellow;

If we use another <h1> tag, then these styles are font-size: 120px;
not applicable. Once again we have to write all the
styles. With this code is increasing. So we have to letter-spacing: 90px;
use “Outline CSS code”
text-transform: uppercase;

</style>

Note: This style is applicable to all <h1> tags


wherever we use in the web page. It is like global
effect to all <h1> tags.
So, lot of code is reduced with “Outline CSS”.

Another Example:

File: cssfile2.html

<style>

h2 {

color: yellow;

background-color: blue;

font-size: 80px;

letter-spacing: 20px;

text-transform: lowercase;

</style>

<h2> Cascading Style Sheets </h2>

Output:
Another Example:

Task:

Give left margin 40 pixels to heading1, 80 pixels to heading2, 120 pixels to heading3, 160 pixels to

heading4, 200 pixels to heading5, 240 pixels to heading6

File: cssfile3.html

<style>

body {

background-color: yellow;

h1 {

color: blue;

margin-left: 40px;

h2 {

color: blue;

margin-left: 80px;

h3 {

color: blue;

margin-left: 120px;

h4 {

color: blue;

margin-left: 160px;

h5 {
color: blue;

margin-left: 200px;

h6 {

color: blue;

margin-left: 240px;

</style>

<h1>Heading1</h1>

<h2>Heading2</h2>

<h3>Heading3</h3>

<h4>Heading4</h4>

<h5>Heading5</h5>

<h6>Heading6</h6>

Output:
 CSS code can be applied in three ways:

1) Tag level CSS

2) Page level CSS

3) Site level CSS

1) Tag level CSS


 Tag level CSS is also called as Inline CSS
we can use style attribute of any HTML element to define style rules. These rules will be applied
to that tag or element only.
Ex: Let us apply “Inline CSS” to <h1> tag and <p> tag
Note: <h1> tag is for “Heading1” and <p> tag is for “Paragraph”
File: taglevelcss.html
<html>

<head>

</head>

<body bgcolor=orange>
<h1 style=color:yellow;background:blue>

This is inline CSS

</h1>

<p style=color:blue;font-size:30px> Inline CSS - An inline style will be used to apply a unique
style for a single element. To use inline styles, add the style attribute to the relevant element.

</p>

</body>

</html>

Output:

2) Page level CSS


 Page level CSS is also called as Inline Page CSS
 Page level CSS is done with <style> tag.
Ex: Let us apply “Page level CSS” to <h1> tag and <p> tag

File: pagelevelcss.html
<html>
<head>

<style>

h1 {

color : yellow;

background : blue;

p{

color : blue;

font-size : 30px;

</style>

</head>

<body bgcolor=orange>

<h1>

This is Page level CSS

</h1>

<p> Page level CSS – Page level CSS will be used to apply a unique style for a single
webpage. To use Page level CSS, add the “style tag” in the web page.

</p>

</body>

</html>

Output:
3) Site level CSS
 Site level CSS is also called as External CSS
 The <link> element is used to include an external stylesheet file in HTML document.
 An external style sheet is a separate file with .css extension. We define all the Style rules
within this file and then we can include this file in any HTML document using <link> element.
We write the following files:
i) external.css
ii) apply.html
File: external.css

h1 {

color : yellow;

background : blue;

p{

color : blue;

font-size : 30px;
}

Once file is saved the following icon will appear:

File: apply.html

<head>

<link rel="stylesheet" href="D:\external.css">

</head>

<body bgcolor=orange>

<h1>

This is Site level CSS

</h1>

<p> Site level CSS – Site level CSS will be used to apply a unique style for all webpages. To use site level
CSS, add the “link tag”.

</p>

Output:
Note: external.css file can be applied to all webpages.

Another Example:

Apply the following CSS properties to h1, h2, h3, h4, h5, h6 tags at tag level, page level, and site level:

a) Text color: blue

b) Background color: yellow

c) Letter spacing: 20px

d) Text Transpose: upper case

File: taglevel.html

<body bgcolor=green>

<h1 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading1


</h1>

<h2 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading2


</h2>

<h3 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading3


</h3>

<h4 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading4


</h4>

<h5 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading5


</h5>

<h6 style=color:blue;background-color:yellow;letter-spacing:20px;text-transpose:uppercase> Heading6


</h6>

Output:

File: pagelevel.html

<style>

h1, h2, h3, h4, h5, h6

color : blue;

background-color : yellow;

letter-spacing : 20px;

text-transpose : uppercase;

</style>

<body bgcolor=green>
<h1> Heading1 </h1>

<h2> Heading2 </h2>

<h3> Heading3 </h3>

<h4> Heading4 </h4>

<h5> Heading5 </h5>

<h6> Heading6 </h6>

Output:

File: sitelevel.css

h1, h2, h3, h4, h5, h6

color : blue;

background-color : yellow;

letter-spacing : 20px;

text-transpose : uppercase;
}

File: sitlelevel.html

<link rel="stylesheet" href="D:\sitelevel.css">

<body bgcolor=green>

<h1> Heading1 </h1>

<h2> Heading2 </h2>

<h3> Heading3 </h3>

<h4> Heading4 </h4>

<h5> Heading5 </h5>

<h6> Heading6 </h6>

Output:

 Observe the following <style> tag:

<style>

p
{

text-align: center;

color: blue;

background-color: yellow;

font-size: 30px;

</style>

Note: The above same CSS code is applicable to all paragraphs.

But, we want to apply different CSS codes to paragraphs i.e. one paragraph in one style and another
paragraph in another style. Then we have to use “CSS id selector”.

The CSS id Selector


The id selector uses the id attribute of an HTML element.

The id of an element is unique within a page, so the id selector is used to select one
unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of
the element.

Example
Let us apply different styles to different paragraphs by using “CSS id selectors” as
follows:

Note: This “CSS id selector” is applying at “Page level”, that means this “CSS id
selectors” are applicable to only one page:

File: paragraph.html

<style>

#p1 {

text-align: center;

color: blue;

background-color: yellow;

font-size: 30px;
}

#p2 {

text-align: left;

color: yellow;

background-color: blue;

font-size: 40px;

#p3 {

text-align: right;

color: pink;

background-color: red;

font-size: 50px;

</style>

<p id="p1">This is paragraph1</p>

<p id="p2">This is paragraph2</p>

<p id="p3">This is paragraph3</p>

Note: Here, #p1, #p2, #p3 are the “CSS id selectors”

Output:
Note: If we want to apply “p1” style to all three paragraphs then we can use “p1” id for
all three paragraphs also as follows:

<p id="p1">This is paragraph1</p>

<p id="p1">This is paragraph2</p>

<p id="p1">This is paragraph3</p>

Similarly, if we want to apply “p1” style to paragraph1 and paragraph2 only then we can
use “p1” id for those two paragraphs.

<p id="p1">This is paragraph1</p>

<p id="p1">This is paragraph2</p>

<p id="p3">This is paragraph3</p>

Like this we can use any “id” for any paragraph.

 Now let us apply “CSS id selectors” at site level also as follows:

File: sitelevel.css

#p1 {

text-align : center;

color : blue;
background-color : yellow;

font-size : 30px;

#p2 {

text-align : left;

color : yellow;

background-color : blue;

font-size : 40px;

#p3 {

text-align : right;

color : pink;

background-color : red;

font-size : 50px;

File: sitelevel.html

<link rel="stylesheet" href="D:\sitelevel.css">

<body bgcolor=green>

<p id="p1"> paragraph1 </p>

<br><br>

<p id="p2"> paragraph2 </p>

<br><br>

<p id="p3"> paragraph3 </p>

Output:
CSS Colors
Colors are specified by:

1) CSS color names (predefined color names)

2) CSS RGB colors (Red, Green, Blue values)

3) CSS HEX colors (Hexadecimal values)

4) CSS HSL (Hue, Saturation, Lightness values)

1) CSS Color Names


In CSS, a color can be specified by using a color name:

File: csscolornames.html
<h1 style="background-color:Tomato;">Tomato</h1>

<h1 style="background-color:Orange;">Orange</h1>

<h1 style="background-color:DodgerBlue;">DodgerBlue</h1>

<h1 style="background-color:MediumSeaGreen;">MediumSeaGreen</h1>

<h1 style="background-color:Gray;">Gray</h1>

<h1 style="background-color:SlateBlue;">SlateBlue</h1>

<h1 style="background-color:Violet;">Violet</h1>

<h1 style="background-color:LightGray;">LightGray</h1>

Output:

2) CSS RGB Colors


In CSS, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)


Each parameter (red, green, and blue) defines the intensity of the color between 0 and
255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value
(255) and the others are set to 0.

To display black, set all color parameters to 0, like this: rgb(0, 0, 0).

To display white, set all color parameters to 255, like this: rgb(255, 255, 255).

File: cssrgb.html

<h1 style="background-color:rgb(255, 0, 0);">rgb(255, 0, 0)</h1>

<h1 style="background-color:rgb(0, 0, 255);">rgb(0, 0, 255)</h1>

<h1 style="background-color:rgb(60, 179, 113);">rgb(60, 179, 113)</h1>

<h1 style="background-color:rgb(238, 130, 238);">rgb(238, 130, 238)</h1>

<h1 style="background-color:rgb(255, 165, 0);">rgb(255, 165, 0)</h1>

<h1 style="background-color:rgb(106, 90, 205);">rgb(106, 90, 205)</h1>

Output:

Another example:

Let us try different shades of black color


File: cssrgbcolors.html

<h1 style="background-color:rgb(0, 0, 0);">rgb(0, 0, 0)</h1>

<h1 style="background-color:rgb(60, 60, 60);">rgb(60, 60, 60)</h1>

<h1 style="background-color:rgb(120, 120, 120);">rgb(120, 120, 120)</h1>

<h1 style="background-color:rgb(180, 180, 180);">rgb(180, 180, 180)</h1>

<h1 style="background-color:rgb(240, 240, 240);">rgb(240, 240, 240)</h1>

<h1 style="background-color:rgb(255, 255, 255);">rgb(255, 255, 255)</h1>

Output:

3) CSS HEX Colors


In CSS, a color can be specified using a hexadecimal value in the form:

#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff
(same as decimal 0-255).
For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and
the others are set to the lowest value (00).

Let us try an example:

File: csshexcolors.html

<h1 style="background-color:#ff0000;">#ff0000</h1>

<h1 style="background-color:#0000ff;">#0000ff</h1>

<h1 style="background-color:#3cb371;">#3cb371</h1>

<h1 style="background-color:#ee82ee;">#ee82ee</h1>

<h1 style="background-color:#ffa500;">#ffa500</h1>

<h1 style="background-color:#6a5acd;">#6a5acd</h1>

Output:

Another Example:

Let us try different shades of black color with “CSS hexadecimal colors”

File: csshexcolors.html
<h1 style="background-color:#000000;">#000000</h1>

<h1 style="background-color:#3c3c3c;">#3c3c3c</h1>

<h1 style="background-color:#787878;">#787878</h1>

<h1 style="background-color:#b4b4b4;">#b4b4b4</h1>

<h1 style="background-color:#f0f0f0;">#f0f0f0</h1>

<h1 style="background-color:#ffffff;">#ffffff</h1>

Output:

4) CSS HSL Colors


In CSS, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)


Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white
File: csshsl.html

<h1 style="background-color:hsl(0, 100%, 50%);">hsl(0, 100%, 50%)</h1>

<h1 style="background-color:hsl(240, 100%, 50%);">hsl(240, 100%, 50%)</h1>

<h1 style="background-color:hsl(147, 50%, 47%);">hsl(147, 50%, 47%)</h1>

<h1 style="background-color:hsl(300, 76%, 72%);">hsl(300, 76%, 72%)</h1>

<h1 style="background-color:hsl(39, 100%, 50%);">hsl(39, 100%, 50%)</h1>

<h1 style="background-color:hsl(248, 53%, 58%);">hsl(248, 53%, 58%)</h1>

Output:
Saturation
Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray

50% is 50% gray, but you can still see the color.

0% is completely gray, you can no longer see the color.

File: csshsl.html

<h1 style="background-color:hsl(0, 100%, 50%);">hsl(0, 100%, 50%)</h1>


<h1 style="background-color:hsl(0, 80%, 50%);">hsl(0, 80%, 50%)</h1>

<h1 style="background-color:hsl(0, 60%, 50%);">hsl(0, 60%, 50%)</h1>

<h1 style="background-color:hsl(0, 40%, 50%);">hsl(0, 40%, 50%)</h1>

<h1 style="background-color:hsl(0, 20%, 50%);">hsl(0, 20%, 50%)</h1>

<h1 style="background-color:hsl(0, 0%, 50%);">hsl(0, 0%, 50%)</h1>

Output:

Lightness
The lightness of a color can be described as how much light you want to give the color,
where 0% means no light (black), 50% means 50% light (neither dark nor light) 100%
means full lightness (white).

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the
lightness from 0% to 100% to get darker/lighter shades:
File: csshsl.html

<h1 style="background-color:hsl(0, 0%, 0%);">hsl(0, 0%, 0%)</h1>

<h1 style="background-color:hsl(0, 0%, 24%);">hsl(0, 0%, 24%)</h1>

<h1 style="background-color:hsl(0, 0%, 47%);">hsl(0, 0%, 47%)</h1>

<h1 style="background-color:hsl(0, 0%, 71%);">hsl(0, 0%, 71%)</h1>

<h1 style="background-color:hsl(0, 0%, 94%);">hsl(0, 0%, 94%)</h1>

<h1 style="background-color:hsl(0, 0%, 100%);">hsl(0, 0%, 100%)</h1>

Output:
CSS Backgrounds
CSS backgrounds specify the background colors and background images.

The following are the CSS Background properties:

1) Background color

2) Background Image

3) Background Repeat

1) CSS background-color
The background-color property specifies the background color.

Example: backgroundcolor.html

<style>

body {

background-color: lightblue;

</style>

<body>

<h1>Hello World!</h1>

<p>This page has a light blue background color!</p>

Output:
2) CSS background-image
The background-image property specifies an image to use as the background.

By default, the background-image property repeats an image both horizontally and vertically.

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic2.jpg");

</style>

<h1>Hello World!</h1>

<p>This page has an image as the background!</p>

Output:
3) CSS background-repeat
By default, the background-image property repeats an image both horizontally and vertically.
Already we observed in the above example.

If the image to be repeated only horizontally then we have to use:

background-repeat: repeat-x;

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic2.jpg");

background-repeat: repeat-x;

</style>

<h1>Hello World!</h1>

<p>Here, a background image is repeated only horizontally!</p>


Output:

To repeat an image vertically, set background-repeat: repeat-y;

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic2.jpg");

background-repeat: repeat-y;

</style>

<h1>Hello World!</h1>

<p>Here, a background image is repeated only vertically!</p>

Output:
To show the background image only once then set: background-repeat: no-repeat;

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic2.jpg");

background-repeat: no-repeat;

</style>

<h1>Hello World!</h1>

<p>The background image is only showing once!</p>

Output:
To cover the image to entire page then set: background-size: cover;

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic2.jpg");

background-size: cover;

</style>

<h1>Hello World!</h1>

<p>This background image is covering entire page!</p>

Output:
Note: if you want to see more clarity of the background image then you can use

JPG images

i.e. width: 1920 pixels and height: 1080 pixels

Example: backgroundimage.html

<style>

body {

background-image: url("D:\pic1.jpg");

background-size: cover;

</style>

<h1>Hello World!</h1>

<p>This background image is covering entire page!</p>

Output:
CSS Borders
CSS Border Properties
The CSS border properties allow to specify the style, width, and color of an element's
border.

The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value

Example: cssborder.html

<style>

p.dotted {border-style: dotted;}

p.dashed {border-style: dashed;}


p.solid {border-style: solid;}

p.double {border-style: double;}

p.groove {border-style: groove;}

p.ridge {border-style: ridge;}

p.mix {border-style: dotted dashed solid double;}

</style>

<h2>The border-style Property</h2>

<p>This property specifies what kind of border to display:</p>

<p class="dotted" style=font-size:30px>A dotted border.</p>

<p class="dashed" style=font-size:30px>A dashed border.</p>

<p class="solid" style=font-size:30px>A solid border.</p>

<p class="double" style=font-size:30px>A double border.</p>

<p class="groove" style=font-size:30px>A groove border.</p>

<p class="ridge" style=font-size:30px>A ridge border.</p>

<p class="mix" style=font-size:30px>A mixed border.</p>

Output:
CSS borders can specified with height, width, color, sides, and rounded borders.

1) Border height and width:

Border height and width can be specified as follows:

Ex: height: 20px; width: 60px;

border-width: thick; (OR) border-width:2px; (OR) border-width: medium;

Example: cssborders.html
<style>

p.solid1 {border-style: solid; border-width: thick; height:40px; width:600px}

p.solid2 {border-style: solid; border-width: medium; height:60px; width:800px}

p.solid3 {border-style: solid; border-width: 10px; height:80px; width:1000px}

</style>

<p class="solid1" style=font-size:30px>A solid border.</p>

<p class="solid2" style=font-size:30px>A solid border.</p>

<p class="solid3" style=font-size:30px>A solid border.</p>

Output:

2) Border color:

Colors can be applied to borders with border-color property.

Example: cssborders.html

<style>

p.dotted {border-style: dotted; border-color:blue}


p.dashed {border-style: dashed; border-color:green}

p.solid {border-style: solid; border-color:orange}

p.double {border-style: double; border-color:tomato}

p.groove {border-style: groove; border-color:voilet}

p.ridge {border-style: ridge; border-color:grey}

p.mix {border-style: dotted dashed solid double; border-color:red}

</style>

<h2>The border-style Property</h2>

<p>This property specifies what kind of border to display:</p>

<p class="dotted" style=font-size:30px>A dotted border.</p>

<p class="dashed" style=font-size:30px>A dashed border.</p>

<p class="solid" style=font-size:30px>A solid border.</p>

<p class="double" style=font-size:30px>A double border.</p>

<p class="groove" style=font-size:30px>A groove border.</p>

<p class="ridge" style=font-size:30px>A ridge border.</p>

<p class="mix" style=font-size:30px>A mixed border.</p>

Output:
3) Border sides:

We can specify the border sides as follows:

p {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: dashed;
}

Example: cssborders.html

<style>

p.border1 {

border-top-style: dotted;

border-right-style: solid;

border-bottom-style: dotted;

border-left-style: dashed;

p.border2 {

border-top-style: solid;
border-right-style: dotted;

border-bottom-style: solid;

border-left-style: dotted;

</style>

<p class="border1" style=font-size:30px>First Border</p>

<p class="border2" style=font-size:30px>Second Border</p>

Output:

4) Rounded Borders:

By using border-radius property, we can specify the rounded borders.

Example: cssborders.hml

<style>

p.round1 {

border: solid;

border-radius: 5px;
}

p.round2 {

border: solid;

border-radius: 8px;

p.round3 {

border: solid;

border-radius: 12px;

p.round4 {

border: solid;

border-radius: 24px;

</style>

<p class="round1" style=font-size:30px>Rounded border style1</p>

<p class="round2" style=font-size:30px>Rounded border style2</p>

<p class="round3" style=font-size:30px>Rounded border style3</p>

<p class="round4" style=font-size:30px>Rounded border style4</p>

Output:
JavaScript
 JavaScript is the Programming Language for the Web.

 JavaScript can calculate, manipulate and validate data.

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

Top 9 Advantages of JavaScript


1. JavaScript is a client side language.
2. JavaScript is an easy language to learn.
3. JavaScript is comparatively fast for the end user.
4. Extended functionality to web pages.
5. No compilation needed.
6. Easy to debug and test.
7. Platform independent.
8. Event-Based Programming language.
9. Procedural programming capabilities

First program of JavaScript:

i) Let us ask customer name

ii) If name is entered then display “You are welcome”

iii) If name is not entered then display an alert message that “Please enter your name”

File: js.html

<script>

function display()

if(document.getElementById("name").value=="")

alert("Please enter your name");

}
else

document.getElementById("p1").innerHTML=document.getElementById("name").value+" you are


welcome";

</script>

<body bgcolor=yellow>

Name <input type="text" id="name"><br><br>

<input type="submit" value="Submit" onclick="display()"><br><br>

<b><p id="p1"></p>

Output:
 Let us take the following details from customer:

i) First name, Last name, Gender, Age, Address, Mobile number, and Email ID

ii) If customer does not enter any value then ask the customer to enter the value.

File: js.html

<script>

function display()

if(document.getElementById("fname").value=="")

alert("Please enter your first name");

else

document.getElementById("p1").innerHTML="Your First Name is:


"+document.getElementById("fname").value;
}

if(document.getElementById("lname").value=="")

alert("Please enter your last name");

else

document.getElementById("p2").innerHTML="Your Last Name is:


"+document.getElementById("lname").value;

if(document.getElementById("gender").value=="")

alert("Please enter your gender");

else

document.getElementById("p3").innerHTML="Your Gender is:


"+document.getElementById("gender").value;

if(document.getElementById("age").value=="")

alert("Please enter your age");

else
{

document.getElementById("p4").innerHTML="Your Age is: "+document.getElementById("age").value;

if(document.getElementById("address").value=="")

alert("Please enter your Address");

else

document.getElementById("p5").innerHTML="Your Address is:


"+document.getElementById("address").value;

if(document.getElementById("mobile").value=="")

alert("Please enter your Mobile Number");

else

document.getElementById("p6").innerHTML="Your Mobile Number is:


"+document.getElementById("mobile").value;

if(document.getElementById("email").value=="")

alert("Please enter your Email ID");


}

else

document.getElementById("p7").innerHTML="Your Email ID is:


"+document.getElementById("email").value;

</script>

<body bgcolor=yellow>

<center>

<h1 style=color:blue><u> Customer Details </u></h1>

<table height=500 widht=400 style=font-size:22px>

<tr>

<td><b>First Name </td>

<td><input type="text" id="fname"></td>

</tr>

<tr>

<td><b>Last Name</td>

<td><input type="text" id="lname"></td>

</tr>

<tr>

<td><b>Gender</td>

<td><input type="text" id="gender"></td>


</tr>

<tr>

<td><b>Age</td>

<td><input type="text" id="age"></td>

</tr>

<tr>

<td><b>Address</td>

<td><input type="text" id="address"></td>

</tr>

<tr>

<td><b>Mobile Number</td>

<td><input type="text" id="mobile"></td>

</tr>

<tr>

<td><b>Email ID</td>

<td><input type="text" id="email"></td>

</tr>

<tr>

<td colspan=2 align=center><input style=font-size:20px type="submit" value="Submit"


onclick="display()"></td>

</tr>

</table>
</center>

<b>

<p id="p1" style=font-size:25px></p>

<p id="p2" style=font-size:25px></p>

<p id="p3" style=font-size:25px></p>

<p id="p4" style=font-size:25px></p>

<p id="p5" style=font-size:25px></p>

<p id="p6" style=font-size:25px></p>

<p id="p7" style=font-size:25px></p>

Output:

Note: If customer does not enter any value then a message will be displayed to enter the value.

Another example:

If customer enters string or symbols instead of number for “age” then display a message that “Please enter
number only”.

Next check entered “age” value should be less than or equal to 100.

File: js.html
<script>

function check()

var a=parseInt(document.getElementById("age").value);

if(Number.isInteger(a)==true)

if(a>100)

alert("Please enter age less than or equal to 100");

else

alert("Your age is:"+a);

else

alert("Please enter number only");

</script>

<body bgcolor=pink>

<h2>

age <input type="text" id="age"><br><br>

<input type="button" value="submit" onclick="check()">


Output:
 Now let us take two numbers from the user and print addition, subtraction, multiplication, division,
modulation, and power results both in message box (by using “alert()” function) and as a paragraph in the
web page with help of Java script.

File: js.html

<script>
function operations()

var i=parseInt(document.getElementById("n1").value);

var j=parseInt(document.getElementById("n2").value);

if(Number.isInteger(i)==true && Number.isInteger(j)==true)

alert("Addition:"+(i+j)+

"\nSubtraction:"+(i-j)+

"\nMultiplication:"+(i*j)+

"\nDivision:"+(i/j)+

"\nModulation:"+(i%j)+

"\nPower:"+(i**j));

document.getElementById("p1").innerHTML="Addition:"+(i+j)+"<br>Subtraction:"+(i-j)+"
<br>Multiplication:"+(i*j)+"<br>Division:"+(i/j)+"<br>Modulation:"+(i%j)+"<br>Power:"+(i**j);

else

alert("Please enter integers only");

</script>

<body bgcolor=pink>

<h2>

Enter first number <input type="text" id="n1"><br><br>

Enter Second number <input type="text" id="n2"><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="operations()"><br><br>

<p id="p1"></p>
Output:

 Now, let us take marks of 5 subjects from the student and display the Grade based on the percentage of
marks.

File: marks.html
<script>

function marks()

var m1=parseInt(document.getElementById("s1").value);

var m2=parseInt(document.getElementById("s2").value);

var m3=parseInt(document.getElementById("s3").value);

var m4=parseInt(document.getElementById("s4").value);

var m5=parseInt(document.getElementById("s5").value);

var percentage=(m1+m2+m3+m4+m5)/5;

if(percentage==100)

alert("Dear student, Your grade is: A+");

else if(percentage>=90 && percentage<=99)

alert("Dear student, Your grade is: A");

else if(percentage>=80 && percentage<=89)

alert("Dear student, Your grade is: B+");

else if(percentage>=70 && percentage<=79)

alert("Dear student, Your grade is: B");

else if(percentage>=60 && percentage<=69)


{

alert("Dear student, Your grade is: C+");

else if(percentage>=50 && percentage<=59)

alert("Dear student, Your grade is: C");

else if(percentage>=40 && percentage<=49)

alert("Dear student, Your grade is: Just Pass");

else

alert("Dear student, You are failed");

</script>

<body bgcolor=pink>

<h1><b><u>Grade Calculation</u></b></h1>

<h2>

Subject1 <input type="text" id="s1"><br><br>

Subject2 <input type="text" id="s2"><br><br>

Subject3 <input type="text" id="s3"><br><br>

Subject4 <input type="text" id="s4"><br><br>

Subject5 <input type="text" id="s5"><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="marks()">


Output

 Now let us take a number from the user and display its multiplication table.

File: multiplicationtable.html

<script>

function multiplication()

var a=parseInt(document.getElementById("n1").value);

var s="";

for(i=1;i<=20;i++)

s=s+(i+" * "+a+" = "+i*a+"<br>");

document.getElementById("p1").innerHTML=s;

</script>
<body bgcolor=pink>

<h2>

Enter a number <input type="text" id="n1"><br><br>

<input type="button" value="Submit" onclick="multiplication()"><br><br>

<p id="p1"></p>

Output:

Note:

We can also use “while loop” for the above multiplication table

while(i<=20)

s=s+(i+" * "+a+" = "+i*a+"<br>");

i+=1;

}
Next Example:

Let us take name from the customer in one web page and display that name in another web page.

We have to write two html files. They are:

1) form1.html

2) display.html

File: form1.html

<script>

function passvalues()

var n=document.getElementById("name").value;

localStorage.setItem("textvalue",n);

</script>

<body bgcolor=pink>

<h1>

<form action="display.html">

Name <input type="text" id="name" style=font-size:25px><br><br>

<input type="submit" value="Submit" onclick="passvalues()" style=font-size:28px>

</form>

File: display.html

<body bgcolor=pink>

<h1>

<p id="p1">

<script>

document.getElementById("p1").innerHTML="Welcome "+localStorage.getItem("textvalue");

</script>
</body>

First open Form1.html

Click on “Submit” button


 Now let us take student details in one web page and display them in another web page.

File: studentdetails.html

<script>

function passvalues()

var a=document.getElementById("studentid").value;

localStorage.setItem("textvalue1",a);

var b=document.getElementById("studentname").value;

localStorage.setItem("textvalue2",b);

var c=document.getElementById("studentaddress").value;

localStorage.setItem("textvalue3",c);

var d=document.getElementById("studentcourse").value;

localStorage.setItem("textvalue4",d);

var e=document.getElementById("studentpnno").value;

localStorage.setItem("textvalue5",e);

var f=document.getElementById("studentdob").value;

localStorage.setItem("date",f);

</script>

<body bgcolor=black>
<center>

<h1 style=color:yellow><u>Student Details Form</u><br><br>

<form action="displaystudentdetails.html">

Student ID: <input type="text" id="studentid" style=border-radius:25px;height:40;width:180;font-


size:25px><br><br>

Student Name: <input type="text" id="studentname" style=border-radius:25px;height:40;width:180;font-


size:25px><br><br>

Student Address: <input type="text" id="studentaddress" style=border-


radius:25px;height:40;width:180;font-size:25px><br><br>

Student Course: <input type="text" id="studentcourse" style=border-


radius:25px;height:40;width:180;font-size:25px><br><br>

Student Phno: <input type="text" id="studentpnno" style=border-radius:25px;height:40;width:180;font-


size:25px><br><br>

Student DOB: <input type="date" id="studentdob" style=border-


radius:25px;height:40;width:180><br><br><br>

<input type="submit" value="Submit" onclick="passvalues()" style=font-size:28px>

</form>

</center>

</body>

File: displaystudentdetails.html

<body bgcolor=yellow>

<h1>

<p id="p1">

<p id="p2">

<p id="p3">

<p id="p4">

<p id="p5">

<p id="p6">

<script>
document.getElementById("p1").innerHTML="Student ID:"+localStorage.getItem("textvalue1");

document.getElementById("p2").innerHTML="Student Name:"+localStorage.getItem("textvalue2");

document.getElementById("p3").innerHTML="Student Address:"+localStorage.getItem("textvalue3");

document.getElementById("p4").innerHTML="Student Course:"+localStorage.getItem("textvalue4");

document.getElementById("p5").innerHTML="Student Phno:"+localStorage.getItem("textvalue5");

document.getElementById("p6").innerHTML="Student DOB:"+localStorage.getItem("date");

</script>

</body>

Output:
 Now let us take employee details in one web page and display them in another web page.

File: employeesform.html

<script>

function passvalues()

var a=document.getElementById("ID").value;

localStorage.setItem("textvalue1",a);

var b=document.getElementById("name").value;

localStorage.setItem("textvalue2",b);

var c=document.getElementById("dept").value;

localStorage.setItem("textvalue3",c);
var d=document.getElementById("desg").value;

localStorage.setItem("textvalue4",d);

var e=document.getElementById("sal").value;

localStorage.setItem("textvalue5",e);

</script>

<body bgcolor=yellow>

<h1>

<form action="employeedisplay.html">

ID <input type="text" id="ID" style=font-size:25px><br><br>

Name <input type="text" id="name" style=font-size:25px><br><br>

Department <input type="text" id="dept" style=font-size:25px><br><br>

Designation <input type="text" id="desg" style=font-size:25px><br><br>

Salary <input type="text" id="sal" style=font-size:25px><br><br>

<input type="submit" value="Submit" onclick="passvalues()" style=font-size:28px>

</form>

File: employeedisplay.html

<body bgcolor=yellow>

<h1>

<p id="p1">

<p id="p2">

<p id="p3">

<p id="p4">

<p id="p5">

<script>
document.getElementById("p1").innerHTML="Employee ID: "+localStorage.getItem("textvalue1");

document.getElementById("p2").innerHTML="Employee Name: "+localStorage.getItem("textvalue2");

document.getElementById("p3").innerHTML="Employee Department:
"+localStorage.getItem("textvalue3");

document.getElementById("p4").innerHTML="Employee Designation:
"+localStorage.getItem("textvalue4");

document.getElementById("p5").innerHTML="Employee Salary: "+localStorage.getItem("textvalue5");

</script>

</body>

First open employeesform.html

Click on Submit button then employeedisplay.html page will be opened as follows:


 In employeesform.html we used localStorage for five times (because of five values like ID, Name,
Department, Designation, Salary)

 Instead of using localStorage for five times, simply we can use it only for one time for five values with
the help of arrays of Java script.

 The following example shows this.

So, we have to files:

1) jsarray.html

2) jsarraydisplay.html

File: jsarray.html

<script>

function passvalues()

var a=document.getElementById("ID").value;

var b=document.getElementById("name").value;

var c=document.getElementById("dept").value;

var d=document.getElementById("desg").value;
var e=document.getElementById("sal").value;

var n=[a,b,c,d,e]

localStorage.setItem("employeevalues",n);

</script>

<body bgcolor=yellow>

<h1>

<form action="jsarraydisplay.html">

ID <input type="text" id="ID" style=font-size:25px><br><br>

Name <input type="text" id="name" style=font-size:25px><br><br>

Department <input type="text" id="dept" style=font-size:25px><br><br>

Designation <input type="text" id="desg" style=font-size:25px><br><br>

Salary <input type="text" id="sal" style=font-size:25px><br><br>

<input type="submit" value="Submit" onclick="passvalues()" style=font-size:28px>

</form>

Note: In the above code: var n=[a,b,c,d,e] is an array of Java script.

File: jsarraydisplay.html

<body bgcolor=yellow>

<h1>

<p id="p1">

<script>

document.getElementById("p1").innerHTML="Employee Details:
"+localStorage.getItem("employeevalues");

</script>

</body>

First open jsarray.html file


After entering the data, click on submit button then jsarraydisplay.html file will be opened with the
following output.

 We want to display the time when user click on the button.


File: displaydate&time.html

<body bgcolor=green>

<button style=font-size:25px onclick="document.getElementById('p1').innerHTML=Date()">The time


is?</button>

<h1>

<p id="p1"></p>

Once button is clicked on then “date and time” will be displayed as follows:
If we want to display “date and time” directly with in the button only then the following code to be
written:

File: displaydate&time.html

<body bgcolor=green>

<button style=font-size:25px onclick="this.innerHTML=Date()">The time is?</button>

Output:
Once button is clicked then “date and time” will be displayed in the button only.

String Handling Functions of Javascript:

string.length: It is used to know the length of a string.

File: jsstringlength.html
<script>

function display()

var str=document.getElementById("s1").value;

document.getElementById("p1").innerHTML = "String Length:"+str.length;

</script>

<body bgcolor=orange>

<h1>

Enter any string <input type="text" id="s1" style=font-size:25px><br><br>

<input type="button" value="Submit" onclick="display()" style=font-size:25px>

<p id="p1"></p>

Output:

After clicking on Submit button, then string length will be displayed.

 Next let us search a word by using string handling function, search function of Javascript as follows:

File: search.html
<script>

function searchword()

var str=document.getElementById("s1").value;

var word=document.getElementById("s2").value;

var pos = str.search(word);

document.getElementById("p1").innerHTML="word is found at:"+pos+" index number position";

</script>

<body bgcolor=green>

<h1>

Enter a string <input type="text" id="s1" style=font-size:25px><br><br>

Enter a word to search <input type="text" id="s2" style=font-size:25px><br><br>

<input type="button" style=font-size:25px value="Submit" onclick="searchword()"><br><br>

<p id="p1"></p>

Output
Once submit button is clicked then index number position of word will be displayed.

string.toUpperCase()

We can convert lowercase string into uppercase string by using “toUpperCase()” function.

File: uppercase.html

<script>

function convert()

var str = document.getElementById("s1").value;

document.getElementById("s1").value = str.toUpperCase();

</script>

<h1>

Enter a string <input type="text" id="s1" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="convert()">

Output:
Once Submit is clicked the lowercase string into uppercase string

 In the same way, we can try toLowerCase() function

string.trim()

We can remove left-side and right-side un-necessary spaces of string by using trim() function.

<script>
function trimming()

var str = document.getElementById("s1").value;

document.getElementById("s1").value = str.trim();

</script>

<body bgcolor=yellow>

<h1>

Enter a string <input type="text" id="s1" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="trimming()">

Output:

Once submit button is clicked then left-side un-necessary spaces will be removed
string.replace(old-string,new-string):

We can replace old-string with new-string by using replace() function.

File: replace.html

<script>

function replacing()

var str1 = document.getElementById("s1").value;

var str2 = document.getElementById("s2").value;

var str3 = document.getElementById("s3").value;

var str4 = str1.replace(str2,str3);

document.getElementById("s1").value = str4;

</script>

<body bgcolor=yellow>

<h1>

Enter a string <input type="text" id="s1" style=font-size:25px><br><br>


Which word you want to replace <input type="text" id="s2" style=font-size:25px><br><br>

Enter new word <input type="text" id="s3" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="replacing()">

Output:

Once Submit button is clicked then apple word is replaced with orange word
string.split()

split() function is used to split a sentence(string) into words(sub-strings).

File: splitting.html

<script>

function splitting()

var str=document.getElementById("s1").value;

document.getElementById("p1").innerHTML=str.split(" ");

</script>

<body bgcolor=yellow>

<h1>

Enter a sentence <input type="text" id="s1" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="splitting()">

<p id="p1"></p>

Output:
Once Submit button is clicked then splitting operation will be done.

string.sort()

we can sort the strings by using sort() function.

File: sorting.html

<script>

function display()

var n1=document.getElementById("strvalues").value;

var n2=n1.split(",");

document.getElementById("p1").innerHTML="Before Sorting: "+n2;

document.getElementById("p2").innerHTML="After Sorting: "+n2.sort();

</script>

<body bgcolor=pink>

<h1>
Enter some strings <input type="text" id="strvalues" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="display()"><br><br>

<p id="p1"></p>

<p id="p2"></p>

Output:

Let us use mathematical ready-made methods of Javascript:

Math.round(value):

round() function is used to round-up the given number.

Ex: 5.678 is rounded as 6

5.456 is rounded as 5

File: rounding.html

<script>

function display()

var n=parseFloat(document.getElementById("i1").value);
document.getElementById("i1").value=Math.round(n);

</script>

<body bgcolor=yellow>

<h1>

Enter a float value <input type="text" id="i1" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="display()">

Output:

Once Submit button is clicked then 5.678 is rounded as 6


 now let us calculate the power of given number

Ex: 102 = 100

103 = 1000

104 = 10000

File: power.html

<script>

function power()

var a=parseInt(document.getElementById("i1").value);

var b=parseInt(document.getElementById("i2").value);

document.getElementById("p1").innerHTML=a+" to the power of "+b+":"+Math.pow(a,b);

</script>

<body bgcolor=yellow>

<h1>

Enter first integer <input type="text" id="i1" style=font-size:25px><br><br>


Enter second integer <input type="text" id="i2" style=font-size:25px><br><br>

<input type="button" style=font-size:25px value="Submit" onclick="power()"><br><br>

<p id="p1"></p>

Output:
Math.sqrt(value)

Ex: sqrt(4) = 2

sqrt(64) = 8

File: squareroot.html

<script>

function display()

var n=parseFloat(document.getElementById("i1").value);

document.getElementById("p1").innerHTML="Square root of "+n+" is:"+Math.sqrt(n);

</script>

<body bgcolor=yellow>

<h1>

Enter an integer <input type="text" id="i1" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="display()"><br><br>

<p id="p1"></p>

Output:
Math.min(), Math.max()

To find minimum and maximum values, we can use min() and max() functions.

<script>

function display()

{
var a=parseInt(document.getElementById("i1").value);

var b=parseInt(document.getElementById("i2").value);

var c=parseInt(document.getElementById("i3").value);

var d=parseInt(document.getElementById("i4").value);

document.getElementById("p1").innerHTML="Minimum value:"+Math.min(a,b,c,d);

document.getElementById("p2").innerHTML="Maximum value:"+Math.max(a,b,c,d);

</script>

<body bgcolor=green>

<h1>

Enter First integer <input type="text" id="i1" style=font-size:25px><br><br>

Enter Second integer <input type="text" id="i2" style=font-size:25px><br><br>

Enter Third integer <input type="text" id="i3" style=font-size:25px><br><br>

Enter Fourth integer <input type="text" id="i4" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="display()"><br><br>

<p id="p1"></p>

<p id="p2"></p>

Output:
sort()

sort() function is used to sort the numbers

File: numberssorting.html

<script>

function display()

var a=parseInt(document.getElementById("i1").value);

var b=parseInt(document.getElementById("i2").value);

var c=parseInt(document.getElementById("i3").value);

var d=parseInt(document.getElementById("i4").value);

var n=[a,b,c,d]

document.getElementById("p1").innerHTML="Before sorting:"+n;

document.getElementById("p2").innerHTML="After sorting:"+n.sort(function(a,b){return a - b});

</script>
<body bgcolor=green>

<h1>

Enter First integer <input type="text" id="i1" style=font-size:25px><br><br>

Enter Second integer <input type="text" id="i2" style=font-size:25px><br><br>

Enter Third integer <input type="text" id="i3" style=font-size:25px><br><br>

Enter Fourth integer <input type="text" id="i4" style=font-size:25px><br><br>

<input type="button" value="Submit" style=font-size:25px onclick="display()"><br><br>

<p id="p1"></p>

<p id="p2"></p>

Output:

 Develop the following form:


 Let us ask the user to enter then number of rows and columns of the table and generate the table.

File: sampletable.html

<html>

<head>

<title>Multiplication Table</title>

<script>

var rows = prompt("How many rows for your multiplication table?");

var cols = prompt("How many columns for your multiplication table?");

createTable(rows, cols);

function createTable(rows, cols)

var j=1;
var output = "<table border='1' width='1000' cellpadding='20'>";

for(i=1;i<=rows;i++)

output = output + "<tr>";

while(j<=cols)

output = output + "<td> </td>";

j = j+1;

output = output + "</tr>";

j = 1;

output = output + "</table>";

document.write(output);

</script>

</head>

<body bgcolor=pink>

</body>

</html>

Note: we can any value to border. Ex: border=’2’ (OR) border=’3’ etc…. then we will see different styles of
borders

Output:
 Let us design the following user form
Note: Password is raj123
After clicking on Create button then the following screen will come.

The following is the coding part:

File: userform.html

<script>

var errors = new Array();


errors[0] = "errFirst";

errors[1] = "errLast";

errors[2] = "errUid";

errors[3] = "errPassword";

errors[4] = "errConfirm";

function validate()

var inputs = new Array();

inputs[0] = document.getElementById('first').value;

inputs[1] = document.getElementById('last').value;

inputs[2] = document.getElementById('uid').value;

inputs[3] = document.getElementById('password').value;

inputs[4] = document.getElementById('confirm').value;

var errorMessages= new Array();

errorMessages[0] = "<p style='color:red'>Please enter your first name!</p>";

errorMessages[1] = "<p style='color:red'>Please enter your last name!</p>";

errorMessages[2] = "<p style='color:red'>Please enter your user id!</p>";

errorMessages[3] = "<p style='color:red'>Please enter your password!</p>";

errorMessages[4] = "<p style='color:red'>Please confirm your password!</p>";

for (i in inputs)

var eMessage = errorMessages[i];

var error= errors[i];

if (inputs[i] == "")

document.getElementById(error).innerHTML = eMessage;

else if (i==4)
{

var first = document.getElementById('password').value;

var second = document.getElementById('confirm').value;

if (second != first)

document.getElementById('errConfirm').innerHTML = "<p style='color: red'>Your passwords don't


match!</p>";

else

document.getElementById(error).innerHTML = "OK!";

else

document.getElementById(error).innerHTML = "OK!";

function finalValidate()

var count = 0;

for(i=0;i<5;i++)

var error = errors[i];

if(document.getElementById(error).innerHTML == "OK!")

count = count + 1;

if(count == 5)

document.getElementById("errFinal").innerHTML = "<b><p style=color:green>YOU ARE


WELCOME!!!</p>";

</script>
<body bgcolor=orange>

<center>

<table id="table1" style=font-size:30px>

<tr>

<td>First Name:</td>

<td><input style=font-size:25px type="text" id="first" onkeyup="validate();" /></td>

<td><p id="errFirst"></p></td>

</tr>

<tr>

<td>Last Name:</td>

<td><input style=font-size:25px type="text" id="last" onkeyup="validate();"/></td>

<td><p id="errLast"></p></td>

</tr>

<tr>

<td>User Id:</td>

<td><input style=font-size:25px type="text" id="uid" onkeyup="validate();"/></td>

<td><p id="errUid"></p></td>

</tr>

<tr>

<td>Password:</td>

<td><input style=font-size:25px type="password" id="password" onkeyup="validate();"/></td>

<td><p id="errPassword"></p></td>

</tr>

<tr>

<td>Confirm Password:</td>
<td><input style=font-size:25px type="password" id="confirm" onkeyup="validate();"/></td>

<td><p id="errConfirm"></p></td>

</tr>

<tr>

<td><input type="button" id="create" value="Create" style=font-size:30px


onclick="validate();finalValidate();"/></td>

<td><p id="errFinal"></p></td>

</tr>

</table>

 Let us design the following web page:

Requirement: When user clicks on the text then another text should be displayed.

Once user clicks on “Click on this text” then “You Are Welcome” message should come as follows:
File: clickontext.html

<body bgcolor=yellow>

<center>

<h1 onclick="this.innerHTML='You Are Welcome!'">Click on this text!</h1>

 Let us design the following web page:

Requirement is: whenever user places the mouse pointer on welcome text then “welcome to my web page”
message should come.
File: mouseover.html

<script>

function trigger()

{
document.getElementById("p1").addEventListener("mouseover", popup);

function popup()

alert("Welcome to my WebPage!!!");

</script>

<body bgcolor=orange onload="trigger()">

<p id="p1" style="font-size:50px; position: fixed; left: 550px; top: 300px;">Welcome!!!</p>

Installation of Pycharm IDE


PyCharm IDE:

1) It is providing Better features when compared with general Python IDLE /IDE

2) PyCharm IDE is best suitable for developing Django projects.

3) PyCharm IDE is developed by Jet brains company

4) PyCharm IDE is providing graphical features (GUI features)

5) PyCharm IDE is Freeware software.

1) Open Google and type: Pycharm


Next click on “yes” button
Computer will be restarted.
In this PyCharm window, we can execute Python programs, HTML programs, CSS programs, Javascript programs
Django projects and multiple types of programs.

Now, let us execute Python programs:


Like this you can try all python programs.
Next Let us execute HTML programs
Now, let us execute another HTML program to display a flower image

Note: Place the Flower image in: C:\Users\ccReddy\PycharmProjects\pythonProject

Note: in the place ccReddy, your name will be there.


Like this you can execute all HTML programs.
Now, let us execute CSS programs
Like this we can execute all HTML, CSS, Javascript programs.

Django
For every web application we need:
1) Front-end
2) Back-end

What is Front-end?
Ans: What end-user is seeing is Front-end

What is back-end?
Ans: What end-user is seeing in Front-end is decided by Back-end

What are the Front-end Technologies?


Ans:
HTML
CSS
Javascript
DOM (Document Object Model) (Note: In every program, we used this
statement  document.getElementById(). This code is related to DOM)
Bootstrap

Back-end Technologies:
Python
Django
Databases
Full-stack web developer: Both Front-end and Back-end Technologies

Important points about Django:


1) Django is a back-end web development Framework.

2) Django makes it easier to build better web apps more quickly and with
less code.
Note: official website of Django is: www.djangoproject.com

3) When Django is invented and who invented?


Ans: 2003 by Adrian Holovaty, Simon Willison
(Note: In google, just type: django is invented in)

4) Django is Freeware (no need to pay single paisa) and open-source


(we can customize according our requirements)

5) Django framework is completely written in python

6) Django is maintained by DSF (Django Software Foundation)


What are famous web applications which are developed by using Django:

(just type in google: top 10 django apps)


(and also just type in google: 25 of the most popular python and Django websites)
Top 5 features of Django:

(Note: In www.djangoproject.com  click on overview then these features will be


displayed)

1. Ridiculously fast.
Django was designed to help developers take applications from concept to completion
as quickly as possible.

i.e. Very quick web development is possible with Django.

95% code is provided by Django, we have to write just 5% code.

In 5minutes we can develop a small web application.

2. Fully Loaded:

Django includes dozens of extras you can use to handle common Web development
tasks. Django takes care of user authentication, content administration, site maps, and
many more tasks

So, all common web application related tasks are fully loaded automatically.

3. Reassuringly secure:

Django takes security seriously and helps developers avoid many common
security mistakes, such as SQL injection, cross-site scripting, cross-site request
forgery and clickjacking. Its user authentication system provides a secure way to
manage user accounts and passwords.

i.e. Django is providing complete security to the web application

Simply we have to specify {%csrf_token%} in the code then CSRF will be activated in the
web application.

4. Exceedingly Scalable:

Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale
to meet the heaviest traffic demands.

i.e. Our web application can be scalable to handle any number of requests from the users.

5. Incredibly Versatile

Companies, organizations and governments have used Django to build all sorts
of things — from content management systems to social networks to scientific
computing platforms.

So, with Django all domains web applications can be developed very easily and quickly.

All web applications are developed based on MVC architecture


MVC Architecture:

MVC stands for Model, View, Controller.

MVC Architecture:

1. MVC stands for Model, View and Controller.


2. Model represents the data
3. View is the User Interface.
4. Controller is the request handler.

Detailed Explanation:

Model represents the data

Model: Model represents the shape of the data. A class in C# is used to describe a
model. Model objects store data retrieved from the database.

Note: Model contains Database logic

View is the User Interface.

View: View in MVC is a user interface. View display model data to the user and also
enables them to modify them.

Note: View contains Presentation logic like HTML, CSS, Javascript logics.

Controller is the request handler.

Controller: The controller handles the user request. Typically, the user uses the view and
raises an HTTP request, which will be handled by the controller. The controller processes
the request and returns the appropriate view as a response.
Note: Controller contains business logic

Django follows MVT design pattern

M – Model

V – View

T – Template

The following is the diagrammatic representation of MVT

Here, a user requests for a resource to the Django, Django works as a controller and check to the
available resource in URL.

If URL maps, a view is called that interact with model and template, it renders a template.

Django responds back to the user and sends a template as a response.

Detailed Explanation:

The MVT (Model View Template) is a software design pattern. It is a collection of three important
components Model View and Template. The Model helps to handle database. It is a data access layer
which handles the data.

The Template is a presentation layer which handles User Interface part completely. The View is used to
execute the business logic and interact with a model to carry data and renders a template.

So, control is handled by the Django framework itself. There is no separate controller and complete
application is based on Model View and Template. That’s why it is called MVT application.

Installation steps of Django:


Next we are going to see that “How to create a Django project”

Creating First Django project:


Now open PyCharm
in the above window, there are four buttons. They are:

1)This Window – Replace the new project in existing window

2)New Window – new Project will be opened in a new window

3)Attach - Attaching the new project to the already opened projects.

4)Cancel – Cancel to open the new project

The following is the “First Django Project”


The following is the directory structure of First Django project:
Here,

init = Initialization

asgi = Asynchronous Server Gateway Interface

urls = Uniform Resource Locators

wsgi = Web Server Gateway Interface

In the above First Django project directory structure, The following files are very important and these files we use
regularly:

1) Settings.py
2) urls.py
3) manage.py

We regularly do coding in the above three files.

After Explaining the above three files then remaining directories and files will be explained.

1) settings.py

“settings.py” is a python file and it is used to specify all required settings for Django project.

Settings like: which applications should be used in Django project, Which database should be used in Django
project, Which templates should be used in Django project etc……… will be specified in “settings.py” file.

The following are the general settings of Django Project in “settings.py” file:

1) BASE DIRECTORY of Django project is automatically set


2) SECURITY KEY for Django project is automatically generated.

3) Default APPLICATIONS which are required for Django project are automatically installed and set automatically.

4) Database is automatically set.

For example: In mobile phone also, “settings” will be existed. We set all our required settings for mobile phone in
“settings” window. Similarly, we specify all required settings in “settings.py” file.

2) urls.py

It is also a Python file

urls = Uniform Resource Locators

Examples of URLs:

For example, let us take gmail.com website

Whenever user clicks on "login" link then control goes to this URL: gmail.com/login.html

Whenever user clicks on "Inbox" link then control goes to this URL: gmail.com/inbox.html

Whenever user clicks on "compose" link then control goes to this URL: gmail.com/compose.html

Similarly, in our Django project, whatever URLS are there, then those URLS are mentioned/specified in "urls.py"
file.

3) manage.py

It is also a Python File.

Django project is administered by manage.py file.

So, manage.py will perform administration work for Django project.

manage.py file will communicate to settings.py file automatically to perform the administration work
according to the settings specified in settings.py file.

Now we are going to see other files and directories of Django project.

4) wsgi.py

It is also Python File.

wsgi stands for Web Server Gateway Interface.

wsgi.py file is acting as an interface between web servers and web applications.

wsgi.py file is automatically created in Django project to play an important role between web servers
and web applications.

5) asgi.py

It is also a Python File.

asgi stands for Asynchronous Server Gateway Interface.


asgi is advanced concept to wsgi

asgi provides the advanced features when compared with wsgi

Next we are going to see: WEB SERVER

WEB SERVER:

 A Django project is a collection of applications

The following is diagrammatic representation of “Django Project”

To run the “Django project”, we need a web server.

Web server provides an environment to run “Django Project” (OR) Web Server is used to execute the
Django project”

 Web server is represented diagrammatically as follows:

Whenever client sends the request, First “Web server” receives the request and sends that request to
the appropriate application of Django project. This is shown diagrammatically as follows:
1) Client sends the request to WEB SERVER

2) WEB SEVER will send request to appropriate application of Django Project

3) The appropriate application will process the request and sends the response to WEB SERVER through

Django Project.

4) WEB SERVER sends that response to the client.

Note: WEB SERVER is also called as Development Server

How to start Development Server in Django

Open PyCharm IDE

Go to Terminal window of PyCharm window

Type the following command:

py manage.py runserver

(OR)

python mangage.py runserver


Next click on http://127.0.0.1:8000/
After clicking on the link immediately browser will be opened and Development Server will be running
as follows:
Another way to run Development Server of Django:

 After typing py manage.py runserver in Terminal window of PyCharm IDE, next open browser and
type: http://127.0.0.1:8000/ and press enter key.
Another way to run Development Server in Django:

 After typing py manage.py runserver in Terminal window of PyCharm IDE, next open browser and
type: http: //localhost:8000 and press enter key.

http: //127.0.0.1:8000/

Here, http stands for Hyper Text Transfer Protocol

HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files, such as text, graphic images,
sound, video, and other multimedia files, on the World Wide Web.

127.0.0.1 is the localhost

localhost is a hostname that refers to the current computer.

8000 is the default port number where Django development server is running.
How to stop Development Server in Django

Previously, we typed py manage.py runserver command in Terminal window, here press ctrl + c
buttons.

After pressing ctrl + c buttons, go to browser and press refresh button to check whether WEB SERVER is
stopped or not. Once WEB SERVER is stopped then an error message will be displayed as follows:
Note: If we want to restart the WEB SERVER then we can give py manage.py runserver command in the
Terminal.

How to run Development Server with another port number:

In the Terminal window of PyCharm IDE, type: py manage.py runserver 8888

Note: 8888 is new port number.

Next click on http://127.0.0.1:8888 link


After click on the link, browser will be opened with 8888 port number as follows:
Note: It is always recommended the pre-defined port number 8000

How to create an “application” in Django Project:

 One Django project is a collection of applications.

 To create an application under Django project, do the following steps:

i) Open PyCharm IDE

ii) Go to Terminal window

iii) Type this command:

cd firstdjangoproject

Here, cd stands for “Change Directory”

Note: “firstdjangoproject” is the name of Django project.

Note: In the Terminal Window, if already “firstdjangoproject” directory is present then no need to give “cd
firstdjangoproject” command

iv) Next type this command:

py manage.py startapp firstapp


Note: “firstapp” is the name of the application.

Note: If py manage.py startapp FirstApp command does not work in Terminal then execute in the
command prompt.

So, under “FirstDjangoProject”, “firstapp” application is created.


Under “firstapp” directory, the following files and directory will be automatically created:

1) migrations directory

2) __init__.py file

3) admin.py file

4) apps.py file

5) models.py file

6) tests.py file
7) views.py file

Note: “migrations” directory is related to Database purpose.

 So, one directory and six python files will be existed under firstapp directory.

 The following is the “Directory structure” of “firstapp”

 The following is the complete “Directory Structure” of “FirstDjangoProject”. In the following directory
structure, we can see that “firstapp” is created under “FirstDjangoProject” directory.

Whenever request comes to server then view component of application will send the response.
 So, the diagram of view is separately represented here:

 So the server sends the request to an appropriate application, in that application, view will receive the
request and send the response.

So, view will receive the request and process the request and send the response. This is called business
logic. So, view contains the business logic. View is represented with view.py file.

 views are two types:


First let us see about “Function based views”

Function Based views:

Function-based views are views in Django that are defined by functions.

Note: After completing “Function Based views”, we will see “Class Based views”

 Let us develop one Django application by using “Function Based Views”

Steps to develop Django application by using “Function Based Views”

1. start Django project

2. Within Django project, start application

3. Add the application to the Django project in settings.py file

4. Define view function inside views.py file

5. Define url pattern for view function inside urls.py file

6. Run server

7. Send request from the browser

Let us the above steps practically

1) Start Django Project


Now open PyCharm
in the above window, there are four buttons. They are:

1)This Window – Replace the new project in existing window

2)New Window – new Project will be opened in a new window

3)Attach - Attaching the new project to the already opened projects.

4)Cancel – Cancel to open the new project

The following is the “First Django Project”


2) Within Django project, start application
 Now ,we see FirstApp as follows:
3) Add the application to the Django project in settings.py file

Now we are adding the above create application i.e. FirstApp in settings.py file as follows:
4) Define view function inside views.py file
5) Define url pattern for view function inside urls.py file
6) Run server
7. Send request from the browser
Output:
Execution Flow of above 7 steps:

The following is the Execution flow of Django Application (OR) Execution flow of Application of Django
Project:

1) Run server (py manage.py runserver)

2) Once server is started, immediately "settings.py" file will be loaded.

Note: from "settings.py" file, "FirstApp" is loaded

3) Server and application are ready to receive the request from the user.

Note: User will give the request in Browser.

4) User will type the request in Browser as follows:

http://127.0.0.1:8000/FirstApplication

5) Execution control immediately goes to "urls.py" file


6) In "urls.py" file, execution control will go to first parameter of “path” path('FirstApplication/'

7) Next execution control goes to views parameter of path('FirstApplication/', views) in “urls.py” file.

8) Next views module of “FirstApp” is imported with the following line of “urls.py” file:

from FirstApp import views

9) Next execution control goes to “views.py” file to execute hello_world_view() function.

10) hello_world_view() function will be executed. That function is:

def hello_world_view(request):

return HttpResponse('<h1> This is Response from Django Application designed by the great people of
8pm batch</h1>')

11) Next the following output is displayed on the browser:

This is Response from Django Application

Diagrammatic representation of “Execution Flow” of Django application in Django project:

Let us develop Second Django Project:

Simple Requirement is: Display Server Date and Time

Open command prompt by typing cmd in start menu


 open PyCharm IDE
Next open Terminal
 The following is the directory structure of FirstApp
In the above code:

s = '<h1> The Current Date and Time at Server is:'+str(date)+'</h1>'


return HttpResponse(s)

The above two lines can also be written as a single line:

return HttpResponse('<h1> The Current Date and Time at Server is:'+str(date)+'</h1>')


After typing the above command press enter key and open browser
After entering the above URL, press enter key then the following output will be displayed.
Next topic: Single Application with multiple views:
We can define multiple views in a single application of Django Project.

Previously, we have defined single view in single application as follows:


The following diagram shows multiple views in a single application:

Steps:

1) Start Project

2) Start Application

3) Add application to the project inside “settings.py” file

4) Define view functions inside views.py file

5) Define url patterns in urls.py file

6) run server

7) send request in browser

These steps are seen practically as follows:

1) Start Project
Open PyCharm

2) Start Application
3) Add application to the project inside “settings.py” file
4) Define view functions inside views.py file
5) Define url patterns in urls.py file
6) run server
7) send request in browser
Next topic: Multiple applications in one Django Project:

We can define multiple applications in one Django project as follows:


Steps to develop Fourth Django Project:

1) Start FourthDjangProject

2) start two applications. One is “greetingapp” and second one is “timeapp”

3) Add two applications to the project, inside of “settings.py” file

4) Define “greetings_view()” function in “views.py” file of “greetingapp”

And define “time_info_view()” function in “views.py” file of “timeapp”

5) Define URL patterns in “urls.py” file

6) Run Server

7) Send requests in browser.

These steps are seen practically as follows:

1) Start Project
Open PyCharm Window
2) start two applications. One is “greetingapp” and second one is “timeapp”

“greetingapp” and “timeapp” are seen in PyCharm window as follows:


3) Add two applications to the project, inside of “settings.py” file
4) Define “greetings_view()” function in “views.py” file of “greetingapp” and define “time_info_view()”
function in “views.py” file of “timeapp”

First define “greetings_view()” function in “views.py” file of “greetingapp” as follows:


Next define “time_info_view()” function in “views.py” file of “timeapp” as follows:
5) Define URL patterns in “urls.py” file
6) Run Server
7) Send requests in browser:
Next topic: Creating “urls.py” at application level

Upto this we have seen “urls.py” file at project level

Now we are going to create “urls.py” file at application level. Before this, we have to know “why we
have to create urls.py file at applications level.

For example, we have one Django project namely “Fifth Django Project”
we have to write five url patterns in “urls.py” file of “FifthDjangoProject”

If we want to re-use testapp of Fifth Django Project in Sixth Django Project then we have to write again
five url patterns of testapp. Similarly if we want to re-use testapp of Fifth Django Project in other Django
Projects then also we have to write five url patterns of testapp. So, url pattern related code is increasing.
So, to reduce this repetition of url pattern related coding, we have to create urls.py file at application level.

The following are steps to create “urls.py” at application level:

Project Name is: Fifth Django Project

1) Start “Fifth Django Project”

2) Start “test app” in “Fifth Django Project” (Note: “test app” is the application name)

3) Add “test app” application to “Fifth Django Project”

4) Define five view functions in “views.py” file of “test app” application (Note: Five view functions are:
first_view(), second_view(), third_view(), fourth_view(), and fifth_view() )

5) Create “urls.py” file in “test app” and specify five url patterns.

6) Include “urls.py” file of “test app” in Fifth Django Project’s “urls.py” file

7) Run Server

8) Send Requests in browser.

These steps are seen practically as follows:

1) Start “Fifth Django Project”


open PyCharm
2) Start “test app” in “Fifth Django Project”

Note: “test app” is the application name


3) Add “test app” application to “Fifth Django Project”
4) Define five view functions in “views.py” file of “test app” application

Note: Five view functions are: first_view(), second_view(), third_view(), fourth_view(), and fifth_view()
5) Create “urls.py” file in “test app” and specify five url patterns:

Note: Five url patterns are:


Type the programming lines in “urls.py” file of “test app” as follows:
6) Include “urls.py” file of “test app” in Fifth Django Project’s “urls.py” file
7) Run Server
8) Send Requests in browser
Output:

Like this we can the following URLs:

http://127.0.0.1:8000/testapp/second

Next

http://127.0.0.1:8000/testapp/third

Next

http://127.0.0.1:8000/testapp/fourth

Next

http://127.0.0.1:8000/testapp/fifth

Next topic: Re-using an application of One Django Project into another Django Project

 Applications of Django Project are Re-usable.

 According to our requirements we can re-use the applications one Django project into another Django
project.

 For example, in Fifth Django Project we have test app. Let us use this test app in Sixth Django Project

Steps:

1) start “Sixth Django Project”

2) copy “test app” of “Fifth Django Project” into “Sixth Django Project”

3) Add “test app” in “settings.py” file of “Sixth Django Project”


4) Include “test app” url in “urls.py” file of “Sixth Django Project”

5) Run Server

6) Send the requests from browser

These steps are seen practically as follows:

1) start “Sixth Django Project”

Type cmd in start menu to open command prompt


Open PyCharm
2) copy “test app” of “Fifth Django Project” into “Sixth Django Project”
3) Add “test app” in “settings.py” file of “Sixth Django Project”
4) Include “test app” url in “urls.py” file of “Sixth Django Project”

5) Run Server
6) Send the requests from browser
Like this we can the following URLs:

http://127.0.0.1:8000/testapp/second

Next

http://127.0.0.1:8000/testapp/third

Next

http://127.0.0.1:8000/testapp/fourth

Next

http://127.0.0.1:8000/testapp/fifth

Templates
 up to this we have written presentation logic (HTML Code) in Python file i.e. "views.py" file.

 It is always recommended that Presentation logic (HTML Code) should be placed in HTML files and
business logic (Python Code) in python files i.e. views.py files.

what is Business Logic?

Ans: The programming code (Python Code) which is related to business requirements. we always write
"business logic" in views.py file

In MVT architecture, V (View) represents Business logic


What is Presentation logic?

Ans: The programming code (HTML Code) which is used to present the information effectively to the end
users based on their requests. we always place presentation logic in Templates

In MVT architecture, T (Templates) represent "Presentation logic"

So, Templates are nothing but HTML files.

What is Database logic?

Ans: The programming code (SQL Code) which is used to get the data from database. we always place
database logic in Model.

In MVT architecture, M (Model) represents "Database Logic"

M - Model - Database logic

V - Views - Business Logic

T - Templates - Presentation Logic

 The following is the diagrammatic representation of “Views and Templates”

So, views functions of “views.py” file will use Templates (HTML files).

Now we are going to develop “Template Based projects” in Django.

To develop the “Template based projects” in Django, we have to do the following steps:

1) Start project (Project name: TemplateProject1)

2) Start application (application name: testapp)

3) Create templates folder in outer project folder( i.e. TemplateProject1)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template files (HTML files)

Note: Folder is also called as Directory


4) Add application (i.e. testapp) in “settings.py” file

4a) Add template folder path to “settings.py” file

5) Define view function in “views.py” file i.e. defining business logic in “views.py” file.

6) Define URL pattern for view function in “urls.py” file

7) Run server

8) Send the request from the browser.


1) Start project (Project name: TemplateProject1)
2. Start Application

Open Terminal window in PyCharm IDE

3) Create templates folder in outer project folder( i.e. TemplateProject1)


3a) In “templates” folder, create “testapp” folder
3b)In that “testapp” folder, define template files (HTML files)

We create template file i.e. results.html in “testapp” folder.


Note: In the above screen, File type is “HTML”, so .html file extension need not be typed.
4) Add application (i.e. testapp) in “settings.py” file
4a) Add template folder path to “settings.py” file
5) Define view function in “views.py” file i.e. defining business logic in “views.py” file.

Now we define “template_view(request)” function in “views.py” file of “testapp” application.


Note: render() function is used to get the response from html file (i.e. results.html)

So, We directly write HTML code in "results.html" file but not in "views.py" file.

So that "Presentation logic" is in HTML file and "business logic" in views.py file.

6) Define URL pattern for view function in “urls.py” file


7) Run server
8) Send the request from the browser.
Execution Flow of above program:

http://127.0.01:8000/test  server  urls.py  views.py  results.html i.e. template file

template file sends the response to view function i.e. temple_view(request) function  view function will
send the response to end-user.

The same execution process is shown as diagram:


Ex:

Expected Output:

Just follow above 8 steps, and type the following code in results.html file.
Code:

<style>
body{
background:yellow;
color:blue;
}
</style>
<h1>This response from Template File.</h1>
<h2>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>Javascript</li>
</ol>

How to pass the data from views.py file to template file (html file):

Template tag is used to pass the data from view function of views.py file to Template File.

Let us send the employee details from view function to template file.

These steps are same:

1) Start project (Project name: TemplateProject1)

2) Start application (application name: testapp)

3) Create templates folder in outer project folder( i.e. TemplateProject1)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template files (HTML files)

Note: Folder is also called as Directory

4) Add application (i.e. testapp) in “settings.py” file

4a) Add template folder path to “settings.py” file

5) Define view function in “views.py” file i.e. defining business logic in “views.py” file.

6) Define URL pattern for view function in “urls.py” file

7) Run server
8) Send the request from the browser.

Just code will be changed in “view.py” file and in “results.html” file

Views.py

from django.shortcuts import render

# Create your views here.


def template_view(request):
emp_dict={'name':'Ravi','dept':'IT'}
return render(request,'testapp/results.html',context=emp_dict)

In the above python code: “emp_dict” is a dictionary and it contains key : value pairs.

results.html

<style>
body{
background:yellow;
color:blue;
}
</style>
<h1>Employee Details: {{name}},{{dept}}</h1>

In the above html code: template tags are: {{name}} and {{dept}}

Note: template tags coding is also called as Jinja2 Code. It is a another scripting language.

Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher
and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like
expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template
language and thus can be used to generate any markup as well as source code.

After this, run the server and send the request in browser as follows:

http://127.0.0.1:8000/test

Output
Let us send dynamic content like date and time from view function to template file (html file)

Follow the same steps as above and just change the code in “views.py” file and in “results.html” file.

views.py

from django.shortcuts import render


import datetime

# Create your views here.


def template_view(request):
dt=datetime.datetime.now()
d={'date':dt}
return render(request,'testapp/results.html',context=d)

(OR)

from django.shortcuts import render


import datetime

# Create your views here.


def template_view(request):
dt=datetime.datetime.now()
d={'date':dt}
return render(request,'testapp/results.html',d)

(OR)

from django.shortcuts import render


import datetime

# Create your views here.


def template_view(request):
dt=datetime.datetime.now()
return render(request,'testapp/results.html',{'date':dt})
results.html

<style>
body{
background:yellow;
color:blue;
}
</style>
<h1>Date and Time: {{date}}</h1>

Output

Next Example:

Expected Output:
Follow the same steps as above. Just change the code in “views.py” file and in “results.html” as follows:

views.py

from django.shortcuts import render


import datetime

# Create your views here.


def template_view(request):
rno=1001
name="Raju"
course="Django"
dt=datetime.datetime.now()
students_dict={"roll_number":rno,"name":name,"course":course,"date":dt}
return render(request,'testapp/results.html',students_dict)

results.html

<style>
body{
background:blue;
color:yellow;
}
</style>

<body>
<h1><u>STUDENT DETAILS</u></h1>
<h2>
<ol>
<li>Student Roll Number: {{roll_number}}</li>
<li>Student Name: {{name}}</li>
<li>Student Course: {{course}}</li>
<li>Joining Date: {{date}}</li>
</ol>
</h2>
</body>

Next open browser and send the request as follows:

http://127.0.0.1:8000/test

******************************************************************

Next requirement is: When request is sent (i.e when URL is passed) immediately, display wishes like
Good Morning, Good Afternoon, Good Evening, Good Night based on the time.

Follow the same steps. They are:

1) Start project (Project name: TemplateProject2)

2) Start application (application name: testapp)

3) Create templates folder in outer project folder( i.e. TemplateProject2)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template file (HTML file i.e. results.html)

Note: Folder is also called as Directory

4) Add application (i.e. testapp) in “settings.py” file

4a) Add template folder path to “settings.py” file

5) Define view function (i.e wish() function) in “views.py” file i.e. defining business logic in “views.py” file.

6) Define URL pattern for view function in “urls.py” file

7) Run server

8) Send the request from the browser.

All these steps are same like above. Just type the following code:

views.py

from django.shortcuts import render


import datetime
# Create your views here.
def wish(request):
dt=datetime.datetime.now()
h=int(dt.strftime('%H'))
msg="Hello Guest !!! Very Good"
if h<12:
msg=msg+" Morning !!!"
elif h<16:
msg = msg + " Afternoon !!!"
elif h<21:
msg = msg + " Evening !!!"
else:
msg = msg + " Night !!!"
response = render(request,'testapp/results.html',{'m':msg})
return response

results.html

<style>
body{
background:yellow;
color:blue;
}
</style>
<h1>{{m}}</h1>

urls.py

from django.contrib import admin


from django.urls import path
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('test/',views.wish)
]

next open browser and type: http://127.0.0.1:8000/test

Output

The above urls.py file can also be written as follows:

urls.py

from django.contrib import admin


from django.urls import path
from testapp import views
from django.conf.urls import url

urlpatterns = [
path('admin/',admin.site.urls),
url(r'^$',views.wish)
]

Description: url(r'^$',views.wish)
Here r stands for regular expression
^$ If we type: http://1270.0.0.1:8000 then immediately result will come. So, URL pattern in not required like
http://127.0.0.1:8000/test
So, if we want to execute directly home page then it will be useful.

In browser, type: http://127.0.0.1:8000

So, no need to give http://127.0.0.1:8000/test

Output:
 If we want to make working of both URLs i.e.

http://127.0.0.1:8000

and also

http://127.0.0.1:8000/test

then, we can write urls.py file as follows:

urls.py

from django.contrib import admin


from django.urls import path
from testapp import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$',views.wish),
url(r'^test/', views.wish),
]

Creating Multiple URLs for one view function:

urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from testapp import views

urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$',views.wish),
url(r'^test/',views.wish),
url(r'^guest/', views.wish),
url(r'^Raju Guest/', views.wish),
]

In the browser, we can give any URL pattern:

http://127.0.0.1:8000

(OR)

http://127.0.0.1:8000/test

(OR)

127.0.0.1:8000/guest

(OR)

http://127.0.0.1:8000/Raju Guest

Next topic: Working with Static Files

CSS files, image files, audio, video files are called as static files

Now we are going to see that how to add these static files to template.

Steps:

1) Start Project (Project Name: staticfilesproject1)

2) Start Application (Application Name: testapp)

3) Create templates folder in outer project folder( i.e. staticfilesproject1)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template files (HTML files)

4) create “static” directory under Outer project directory

4a) Under “static” directory, Create “images” directory

4b) Place some images into “images” folder

5) In “settings.py” file, do the following operations

i) Add Application

ii) Add template folder path

iii) Add static folder path

6) Define view function in “views.py” file

7) Write HTML code in “results.html” regarding static files


8) Define url pattern for view function in “urls.py” file

9) Run Server

10) Send the request from the browser

Let us do these steps practically.

1) Start Project (Project Name: staticfilesproject1)

Open command prompt

2) Start Application (Application Name: testapp)

Open PyCharm IDE


2) Start Application (Application Name: testapp)
3) Create templates folder in outer project folder( i.e. staticfilesproject1)
3a) In “templates” folder, create “testapp” folder
3b)In “testapp” folder, define template files (HTML files)

Let us create results.html file in testapp folder


4) create “static” directory under Outer project directory
4a) Under “static” directory, Create “images” directory
4b) Place some images into “images” folder
5) In “settings.py” file, do the following operations

i) Add Application

ii) Add template folder path

iii) Add static folder path


6) Define view function in “views.py” file
7) Write HTML code in “results.html” regarding static files
Note:

{%load static%}

Here load is a keyword and static is a folder name what we created in 4th step.

{% %} indicates template tag

8) Define url pattern for view function in “urls.py” file


9) Run Server
10) Send the request from the browser
Output:
Next topic: Placing CSS files under “static” directory

Let us place Cascading Style Sheets (CSS) files in “static” folder.

1) Start Project (Project Name: staticfilesproject1)

2) Start Application (Application Name: testapp)

3) Create templates folder in outer project folder( i.e. staticfilesproject1)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template files (HTML files)

4) create “static” directory under Outer project directory


Note: up to 4th step, everything is common.

4a) Under “static” directory, create “css” directory

4b) under “css” directory, create “static1.css” file


4c) In “static1.css” file, type the following code
The following steps are same as in previous example:

5) In “settings.py” file, do the following operations

i) Add Application

ii) Add template folder path

iii) Add static folder path

Note: Code is same as above

6) Define view function in “views.py” file

Note: Code is same as above


7) Write HTML code in “results.html” regarding static files

Now we are going to write HTML Code regarding “css” static file (i.e. static1.css file)

The following steps are as it is like in the above example

8) Define url pattern for view function in “urls.py” file

Note: Code is same as above

9) Run Server

10) Send the request from the browser

http://127.0.0.1:8000/test
Next Example:
If Movie News button is clicked then a Movie News related window will be opened, like that
remaining buttons also.

The following are steps:

1) start project (project name: newsportal)

2) start application (application name: testapp)

3) Create templates folder in outer project folder( i.e. staticfilesproject1)

3a) In “templates” folder, create “testapp” folder

3b)In “testapp” folder, define template files (HTML files)

4) create “static” directory under Outer project directory

4a) Under “static” directory, create “css” directory

4b) under “css” directory, create “news.css” file

4c) under "static" directory, create "images" directory

4d) Under "images" directory, place some images

5) In "settings.py" file, do the following operations:

5a) Add Application

5b) Add template folder path

5c) Add static folder path

6) Define a view function for home page in “views.py” file

7) Write HTML code in "home.html" file and css code in "news.css" file

8) Define a view function for "Educational News" in views.py" file, another view function for
"sports news" and one more view function for "Politics news"

9) In templates folder, under testapp folder, write one more html file for "Educational
news" i.e. educationnews.html

and similarly write sportsnews.html and politics.html

10) Define url patterns for view functions in "urls.py" file

11) Run server

12) Send requests in browser.


Let us do these steps practically.

1) Start Project (Project Name: newsportal)

2) Start Application (Application Name: testapp)

Open PyCharm IDE


3) create templates folder under outer project folder
3a) In “templates” folder, create “testapp” folder
3b)In “testapp” folder, define template files (HTML files)

Note: HTML file name is: home.html


4) create “static” directory under Outer project directory
4a) Under “static” directory, create “css” directory
4b) under “css” directory, create “news.css” file
4c) under "static" directory, create "images" directory
4d) Under "images" directory, place some images
5) In "settings.py" file, do the following operations:

5a) Add Application


5b) Add templates folder path
5c) Add static folder path
6) Define view function in “views.py” file
7) Write HTML code in "home.html" file

In “home.html” file, type {%load static%} line to load static files like CSS files, images
files, audio files, videos files etc..
 To apply CSS styles, we have to include CSS file in “home.html” file by specifying <link>
tag as follows:
<link rel="stylesheet" href="{%static 'css\news.css' %}">
Note: We will define some CSS styles in “news.css” file later.

Next type <h1> tag as follows:

<h1> Welcome to News Portal</h1>

Go to “urls.py” file and type this code:


from testapp import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.home_page_view)
]
Next for testing purpose, run server

In the terminal window, type: py manage.py runserver

and press enter key.


Open browser and enter the following URL and press enter key.

http://127.0.0.1:8000

The following output will come


now go to home.html and add three anchor tags, first one for “Educational News”,
second one for “sports news” and third one for “Politics news”
<center>
<h1>Welcome to News Portal</h1>
<a href="">Educational News</a> &nbsp;&nbsp;&nbsp;
<a href="">Sports News</a> &nbsp;&nbsp;&nbsp;
<a href="">Politics News</a>
</center>
next go to browser and refresh the page

Now you can define some CSS styles in “news.css” file as follows:
body{
background:orange;
}
h1{
color:blue;
}

Now go to browser and press refresh button.


So, orange body background colour is applied and blue colour is applied to heading1

Next go to “views.py” file in “testapp” directory and write the following code
def educational_news_view(request):
news1='Python is the leading programming language in IT industry'
news2='Django is one of the best Python Framwork to develop websites with less
code'
education_dict={'Python':news1,'Django':news2}
return render(request,'testapp/educational_news.html',education_dict)
Next create “educational_news.html” in testapp folder. This testapp folder is existed
under templates folder.
In this “educational_news.html” file also add the following lines:
{%load static%}

<link rel="stylesheet" href="{%static 'css\news.css' %}">

 Next, use <h2> tag in “educational_news.html” page

<h2>EDUCATIONAL NEWS</h2>
And also add <ul> list code:
<ul>
<li>{{Python}}</li>
<li>{{Django}}</li>
</ul>

Go to “urls.py” and type the following code:


url(r'^education/',views.educational_news_view)
Go to “home.html” and type the following code:
<a href="/education">Educational News</a>

Next, run the server by giving the following command in the Terminal

py manage.py runserver
Next, open the browser and type the following URL and press enter key:

http://127.0.0.1:8000

We can add an image of education in “educational_news.html”


<img src="{%static 'images/education.jpg' %}" height="200" width="300">
Now go to browser and press refresh button to see educational related image

Working with “Model” (i.e. Working with Databases)

Database is a collection of data which is represented in the form of Tables (Rows and
Columns)

In Django Framework, default database is: sqlite3


This default database (sqlite3) related settings (configuration) we can see in settings.py
file. The following code is related sqlite3 database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

we have to write the database related coding in models.py file by using Model class.

A Model class is used to represent a table.

Now, let us develop one Django project to use database.

The following are steps:

Step-1: Create Django project (project name: modelproject1)

Step-2: start application (application name: testapp)

Step-3: add application (testapp) in settings.py file

Step-4: Create Employee model class in models.py file

Step-5: Make migrations

Note: “Make migrations” mean that – “Converting Python Model class code into SQL code”.
So, “make migrations” command will convert python model class into SQL code.

Step-6: sqlmigrate operation

“sqlmigrate” command is used to execute SQL converted code to create a table in


database.

Step-7: “migrate” operation

“migrate” command is used to create ready-made tables for admin, auth, contenttypes,
sessions, and testapp applications. We can see these applications in settings.py file.

Step-8: Using admin application (also called as admin interface)

Admin application will be used for administration of project and we can check crated tables,
we can perform CRUD (Create, Read, Update and Delete) operations on tables.

Step-9: Register Model to admin application (admin interface).

Note: Model class name is Employee. So, this Employee model class should be registered in
admin application
Step-10: Add records to table (table name: Employees)

Let us do the above 10 steps practically.

Step-1: Create Django project

Open command prompt, next go to Pycharm Projects folder and type django-admin
startproject modelproject1

Step-2: start application

Go to “PyCharm” IDE and open “modelproject1” and crate “testapp” application


Go to “Terminal” and type

py manage.py startapp testapp

Step-3: add application (testapp) in settings.py file


Step-4: Create Employee model class in models.py file

Note: “models.py” file will be existed in “testapp” directory

Note: Employee model class represents “Employee table”

Write the following code in “models.py” file


class Employee(models.Model):
eno=models.IntegerField()
ename=models.CharField(max_length=64)
esal=models.FloatField()
eaddress=models.CharField(max_length=64)
Step-5: Make migrations

“Make migrations” mean that – “Converting Python Model class code into SQL code”. So,
“make migrations” command will convert python model class into SQL code.

Ex: In the above code, “Employee model class” code will be converted into SQL code. So
that “Employee” table SQL code is ready.

After converting into SQL code, we use “migrate” command to execute that converted SQL
code. So that table will be crated.

 So, to convert “python model class” into SQL code, execute the following command in
“Terminal” window

py manage.py makemigrations
Now, “migrations” directory will be crated under “testapp” directory and it contains one
important file i.e. 0001_initial.py file and this file contains SQL converted code. i.e.
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('eno', models.IntegerField()),
('ename', models.CharField(max_length=64)),
('esal', models.FloatField()),
('eaddress', models.CharField(max_length=64)),
],
),
]
Note: In “0001_initial.py” file, Django creates one extra column i.e. id column and it is
acting as “primary key” and it is auto-incremented.
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID'))

For example, First record id number is 1 and second record id number is 2, like this auto-
incremented.

Step-6: sqlmigrate operation

“sqlmigrate” command is used to execute SQL converted code to create a table in


database.

Type “sqlmigrate” command in “Terminal” window:

py manage.py sqlmigrate testapp 0001

Note: Here, “testapp” is the name of the application and 0001 is the number given to
“initial.py” file. The complete name of the file is “0001_intial.py”
So, Django generated the following SQL code:

CREATE TABLE "testapp_employee" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"eno" integer NOT NULL, "ename" varchar(64) NOT NULL,
"esal" real NOT NULL,
"eaddress" varchar(64) NOT NULL);

Step-7: “migrate” operation

“migrate” command is used to create ready-made tables for admin, auth, contenttypes,
sessions, and testapp applications. We can see these applications in settings.py file.

So, type the following command in terminal:

py manage.py migrate
We can see these messages after giving “py manage.py migrate” command

Apply all migrations: admin, auth, contenttypes, sessions, testapp


Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Applying testapp.0001_initial... OK

Step-8: Using admin application (also called as admin interface)


Admin application will be used for administration of project and we can check crated tables,
we can perform CRUD (Create, Read, Update and Delete) operations on tables.

We can launch admin application by giving the following URL in the browser:

http://127.0.0.1:8000/admin

Note: don’t forget to start the server before going to launch admin application. To start
server, we have to execute “py manage.py runserver” command Terminal window.

we have to pass username and password

For this we have to create “super user”

To create the “super user” and password, go to Pycharm window, next go to Terminal
window and type the following command:

py manage.py createsuperuser

After executing the above command, enter username, email id, and password.

After entering the above details, then “superuser created successfully” message will come.

Now run the server by executing “py manage.py runserver” in Terminal window to check
superuser account.
Next open browser, and type the following URL

http://127.0.0.1:8000/admin

The following is the output


Step-9: Register Model to admin interface.

Open “admin.py” file which is existed under “testapp” directory, which is existed under
“modelproject1” in Pycharm IDE window.

Type the following lines in “admin.py” file


from testapp.models import Employee

admin.site.register(Employee)
Next go to browser and press refresh button. Then we will see “Employees” table under
“testapp” as follows:

Step-10: Add records to table (table name: Employees)

Next click on “Add” button to add the employee record

Next enter the data and click on “save” button


Now employee record is saved. After clicking on “save” button, we will see the following
screen:

Click on “Employee object(1)” to see the record. Then we will see the following employee
details:
 After inserting two records, observe the following window

When you click on “Employees” table the following screen will be displayed:
If we observe the above window, two employee objects are displayed. If we click on the
employee object then that appropriate employee record will be opened but if our
requirement to see all the records at a time then type the following code in “admin.py” file
of “testapp” directory
class EmployeeAdmin(admin.ModelAdmin):
list_display = ['eno','ename','esal','eaddress']

admin.site.register(Employee,EmployeeAdmin)
Next press refresh button in browser then we will see all employee records.

If we want to see in sorted order then click on “ENO” column name then we will see
sorted order of records.

If we want to see “ID” column also then write the following code in “admin.py” file of
“testapp” directory as follows:
class EmployeeAdmin(admin.ModelAdmin):
list_display = ['id','eno','ename','esal','eaddress']

admin.site.register(Employee,EmployeeAdmin)

Next, go to browser and press refresh button then we will see “ID” column also in the
screen

If we want to see sorted order of ID numbers then click on “ID” column
Next, we want to display employee records in the webpage of website.

Write the following code into “views.py” file


from testapp.models import Employee
def employee_info_view(request):
employees=Employee.objects.all()
return render(request,'testapp/results.html',{'employees':employees})

Note: select * from employees will be written in python as: Employee.objects.all()


Next, we have to create “results.html” file. For this, we have to create “templates”
directory under “modelproject1” outer directory. So, right click on “modelproject1” outer
directory, next select “new” option, next select “Directory” option, next type templates and
press enter key.

Next create “testapp” directory under “templates” directory. So, right click on
“templates” directory, next select “new” option, next select “Directory” option and type
testapp and press enter key.
Now create “results.html” file under “testapp” directory. So, right click on “testapp”
directory (which is existed under “templates” directory), next select “New” option, next
select “HTML File” option, next type results.html and press enter key.

Next go to “settings.py” file and add “templates” directory path as follows:


TEMPLATE_DIR = Path.joinpath(BASE_DIR,'templates')

Add this line also in “settings.py” file

'DIRS': [TEMPLATE_DIR]
Next go to “results.html” and type the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Employees Information</h1>
{% if employees %}
<table border="2">
<thead>
<th>Employee Number</th>
<th>Employee Name</th>
<th>Employee Salary</th>
<th>Employee Address</th>
</thead>
{% for emp in employees %}
<tr>
<td>{{emp.eno}}</td>
<td>{{emp.ename}}</td>
<td>{{emp.esal}}</td>
<td>{{emp.eaddress}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No Employee Records Found!!!</p>
{% endif %}
</body>
</html>
Next go to “urls.py” file and write the following code:
from django.conf.urls import url
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.employee_info_view)
]

 Next go to terminal and start the server by typing the following command:
py manage.py runserver

 Next go to browser, and type the following URL and press enter key

http://127.0.0.1:8000

Employee table will be displayed

You might also like