Professional Documents
Culture Documents
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.
Pinterest
Instagram
Udemy
Robinhood
Delivery Hero
Bepro Company
Coursera
Accenture
What are famous web applications which are developed by using Django:
1) HTML5
What is 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..
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:
Note: <b> tag for Bold letters and <i> tag for italic letters.
Output:
In paragraph tag, we can use the following properties:
Output:
Note: default alignment is left
<marquee> tag:
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>
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>
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>
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>
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>
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>
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>
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>
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>
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
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
Output:
<table> tag:
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">
<tr bgcolor=blue>
</tr>
<tr bgcolor=orange>
</tr>
<tr bgcolor=orange>
</tr>
<tr bgcolor=orange>
</tr>
</table>
Output:
Ex:
File: table2.html
<body bgcolor=green>
<center>
<img src="D:\collegeimage1.jpg">
<tr bgcolor=blue>
</tr>
<tr bgcolor=orange>
</tr>
<tr bgcolor=orange>
</tr>
<tr bgcolor=orange>
</tr>
</table>
Output
Ex:
File: table3.html
<body bgcolor=black>
<center>
<tr bgcolor=blue>
</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><a
href="https://www.youtube.com/watch?v=o_hHTUceflw">Demo</a></td>
</tr>
<tr bgcolor=orange>
<td style=font-size:20px><b><a
href="https://www.youtube.com/watch?v=7UETinXc1_g">Demo</a></td>
</tr>
</table>
Output:
HTML Lists
HTML lists allow web developers to group a set of related items in lists.
Example:
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:
<body bgcolor=yellow>
<h1>
<ul>
</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>
<ul>
</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.
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>
</ol>
</h1>
</body>
Output:
<video> tag
Ex:
</video>
File: videos1.html
<body bgcolor=yellow>
</video>
</video>
</video>
Output:
File: videos2.html
<body bgcolor=green>
<center>
<br>
</video>
<br><br><br>
Lenovo IdeaPad S540
<br>
</video>
Output
File: videos3.html
<body bgcolor=blue>
<center>
<table border=True>
<tr bgcolor=green>
<tr bgcolor=orange>
<br>
<ul style=color:green>
<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>
</td>
</tr>
<tr bgcolor=orange>
<br>
<ul style=color:green>
<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>
</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.
An <input> element can be displayed in many ways, depending on the type attribute.
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)
File: form1.html
<body bgcolor=blue>
<form>
<h2 style=color:yellow>
First name
Last name
<input type="text"><br><br>
Gender:<br>
<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>
</form>
Output:
<body bgcolor=pink>
<b>
<form>
Name
Phone
Email
<input type="email" name="email_address" required><br><br>
<fieldset>
</fieldset>
<br><br>
<fieldset>
<legend>Extras</legend>
</fieldset>
<br><br>
Pickup Date/Time
Pickup Place
</select>
<br><br>
Dropoff Place
<datalist id="destinations">
<option value="Airport">
<option value="Beach">
</datalist>
<br>
Special Instructions
<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()
</script>
</head>
<body bgcolor=blue>
<img src="D:\c1.jpg" height=400 widht=400><br>
<form>
<h2 style=color:yellow>
First name
Last name
Gender:<br>
<br><br>
Age
Mobile Number
Address
Hobbies:<br>
<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>
Output:
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.
File: helloworld.html
<html>
<head>
<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:
File: cssfile1.html
<style>
h1 {
color: blue;
background-color: yellow;
font-size: 180px;
letter-spacing: 90px;
text-transform: uppercase;
</style>
Output:
Note: The code between <style> and </style> tags is CSS code.
Note:
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>
Another Example:
File: cssfile2.html
<style>
h2 {
color: yellow;
background-color: blue;
font-size: 80px;
letter-spacing: 20px;
text-transform: lowercase;
</style>
Output:
Another Example:
Task:
Give left margin 40 pixels to heading1, 80 pixels to heading2, 120 pixels to heading3, 160 pixels to
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:
<head>
</head>
<body bgcolor=orange>
<h1 style=color:yellow;background:blue>
</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:
File: pagelevelcss.html
<html>
<head>
<style>
h1 {
color : yellow;
background : blue;
p{
color : blue;
font-size : 30px;
</style>
</head>
<body bgcolor=orange>
<h1>
</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;
}
File: apply.html
<head>
</head>
<body bgcolor=orange>
<h1>
</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:
File: taglevel.html
<body bgcolor=green>
Output:
File: pagelevel.html
<style>
color : blue;
background-color : yellow;
letter-spacing : 20px;
text-transpose : uppercase;
</style>
<body bgcolor=green>
<h1> Heading1 </h1>
Output:
File: sitelevel.css
color : blue;
background-color : yellow;
letter-spacing : 20px;
text-transpose : uppercase;
}
File: sitlelevel.html
<body bgcolor=green>
Output:
<style>
p
{
text-align: center;
color: blue;
background-color: yellow;
font-size: 30px;
</style>
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 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>
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:
Similarly, if we want to apply “p1” style to paragraph1 and paragraph2 only then we can
use “p1” id for those two paragraphs.
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
<body bgcolor=green>
<br><br>
<br><br>
Output:
CSS Colors
Colors are specified by:
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:
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
Output:
Another example:
Output:
#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).
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:
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
Output:
Saturation
Saturation can be described as the intensity of a color.
50% is 50% gray, but you can still see the color.
File: csshsl.html
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
Output:
CSS Backgrounds
CSS backgrounds specify the background colors and background images.
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>
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>
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.
background-repeat: repeat-x;
Example: backgroundimage.html
<style>
body {
background-image: url("D:\pic2.jpg");
background-repeat: repeat-x;
</style>
<h1>Hello World!</h1>
Example: backgroundimage.html
<style>
body {
background-image: url("D:\pic2.jpg");
background-repeat: repeat-y;
</style>
<h1>Hello World!</h1>
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>
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>
Output:
Note: if you want to see more clarity of the background image then you can use
JPG images
Example: backgroundimage.html
<style>
body {
background-image: url("D:\pic1.jpg");
background-size: cover;
</style>
<h1>Hello World!</h1>
Output:
CSS Borders
CSS Border Properties
The CSS border properties allow to specify the style, width, and color of an element's
border.
Example: cssborder.html
<style>
</style>
Output:
CSS borders can specified with height, width, color, sides, and rounded borders.
Example: cssborders.html
<style>
</style>
Output:
2) Border color:
Example: cssborders.html
<style>
</style>
Output:
3) Border sides:
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>
Output:
4) 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>
Output:
JavaScript
JavaScript is the Programming Language for the Web.
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=="")
}
else
</script>
<body bgcolor=yellow>
<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=="")
else
if(document.getElementById("lname").value=="")
else
if(document.getElementById("gender").value=="")
else
if(document.getElementById("age").value=="")
else
{
if(document.getElementById("address").value=="")
else
if(document.getElementById("mobile").value=="")
else
if(document.getElementById("email").value=="")
else
</script>
<body bgcolor=yellow>
<center>
<tr>
</tr>
<tr>
<td><b>Last Name</td>
</tr>
<tr>
<td><b>Gender</td>
<tr>
<td><b>Age</td>
</tr>
<tr>
<td><b>Address</td>
</tr>
<tr>
<td><b>Mobile Number</td>
</tr>
<tr>
<td><b>Email ID</td>
</tr>
<tr>
</tr>
</table>
</center>
<b>
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)
else
else
</script>
<body bgcolor=pink>
<h2>
File: js.html
<script>
function operations()
var i=parseInt(document.getElementById("n1").value);
var j=parseInt(document.getElementById("n2").value);
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
</script>
<body bgcolor=pink>
<h2>
<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)
else
</script>
<body bgcolor=pink>
<h1><b><u>Grade Calculation</u></b></h1>
<h2>
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++)
document.getElementById("p1").innerHTML=s;
</script>
<body bgcolor=pink>
<h2>
<p id="p1"></p>
Output:
Note:
We can also use “while loop” for the above multiplication table
while(i<=20)
i+=1;
}
Next Example:
Let us take name from the customer in one web page and display that name in another web page.
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">
</form>
File: display.html
<body bgcolor=pink>
<h1>
<p id="p1">
<script>
document.getElementById("p1").innerHTML="Welcome "+localStorage.getItem("textvalue");
</script>
</body>
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>
<form action="displaystudentdetails.html">
</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">
</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("p3").innerHTML="Employee Department:
"+localStorage.getItem("textvalue3");
document.getElementById("p4").innerHTML="Employee Designation:
"+localStorage.getItem("textvalue4");
</script>
</body>
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.
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">
</form>
File: jsarraydisplay.html
<body bgcolor=yellow>
<h1>
<p id="p1">
<script>
document.getElementById("p1").innerHTML="Employee Details:
"+localStorage.getItem("employeevalues");
</script>
</body>
<body bgcolor=green>
<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>
Output:
Once button is clicked then “date and time” will be displayed in the button only.
File: jsstringlength.html
<script>
function display()
var str=document.getElementById("s1").value;
</script>
<body bgcolor=orange>
<h1>
<p id="p1"></p>
Output:
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;
</script>
<body bgcolor=green>
<h1>
<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()
document.getElementById("s1").value = str.toUpperCase();
</script>
<h1>
Output:
Once Submit is clicked the lowercase string into uppercase string
string.trim()
We can remove left-side and right-side un-necessary spaces of string by using trim() function.
<script>
function trimming()
document.getElementById("s1").value = str.trim();
</script>
<body bgcolor=yellow>
<h1>
Output:
Once submit button is clicked then left-side un-necessary spaces will be removed
string.replace(old-string,new-string):
File: replace.html
<script>
function replacing()
document.getElementById("s1").value = str4;
</script>
<body bgcolor=yellow>
<h1>
Output:
Once Submit button is clicked then apple word is replaced with orange word
string.split()
File: splitting.html
<script>
function splitting()
var str=document.getElementById("s1").value;
document.getElementById("p1").innerHTML=str.split(" ");
</script>
<body bgcolor=yellow>
<h1>
<p id="p1"></p>
Output:
Once Submit button is clicked then splitting operation will be done.
string.sort()
File: sorting.html
<script>
function display()
var n1=document.getElementById("strvalues").value;
var n2=n1.split(",");
</script>
<body bgcolor=pink>
<h1>
Enter some strings <input type="text" id="strvalues" style=font-size:25px><br><br>
<p id="p1"></p>
<p id="p2"></p>
Output:
Math.round(value):
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>
Output:
103 = 1000
104 = 10000
File: power.html
<script>
function power()
var a=parseInt(document.getElementById("i1").value);
var b=parseInt(document.getElementById("i2").value);
</script>
<body bgcolor=yellow>
<h1>
<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);
</script>
<body bgcolor=yellow>
<h1>
<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>
<p id="p1"></p>
<p id="p2"></p>
Output:
sort()
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;
</script>
<body bgcolor=green>
<h1>
<p id="p1"></p>
<p id="p2"></p>
Output:
File: sampletable.html
<html>
<head>
<title>Multiplication Table</title>
<script>
createTable(rows, cols);
var j=1;
var output = "<table border='1' width='1000' cellpadding='20'>";
for(i=1;i<=rows;i++)
while(j<=cols)
j = j+1;
j = 1;
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.
File: userform.html
<script>
errors[1] = "errLast";
errors[2] = "errUid";
errors[3] = "errPassword";
errors[4] = "errConfirm";
function validate()
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;
for (i in inputs)
if (inputs[i] == "")
document.getElementById(error).innerHTML = eMessage;
else if (i==4)
{
if (second != first)
else
document.getElementById(error).innerHTML = "OK!";
else
document.getElementById(error).innerHTML = "OK!";
function finalValidate()
var count = 0;
for(i=0;i<5;i++)
if(document.getElementById(error).innerHTML == "OK!")
count = count + 1;
if(count == 5)
</script>
<body bgcolor=orange>
<center>
<tr>
<td>First Name:</td>
<td><p id="errFirst"></p></td>
</tr>
<tr>
<td>Last Name:</td>
<td><p id="errLast"></p></td>
</tr>
<tr>
<td>User Id:</td>
<td><p id="errUid"></p></td>
</tr>
<tr>
<td>Password:</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><p id="errFinal"></p></td>
</tr>
</table>
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>
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>
1) It is providing Better features when compared with general Python IDLE /IDE
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
Back-end Technologies:
Python
Django
Databases
Full-stack web developer: Both Front-end and Back-end Technologies
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
1. Ridiculously fast.
Django was designed to help developers take applications from concept to completion
as quickly as possible.
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.
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.
MVC Architecture:
Detailed Explanation:
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.
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: 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
M – Model
V – View
T – Template
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.
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.
init = Initialization
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
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:
3) Default APPLICATIONS which are required for Django project are automatically installed and set automatically.
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
Examples of URLs:
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
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
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
WEB SERVER:
Web server provides an environment to run “Django Project” (OR) Web Server is used to execute the
Django project”
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
3) The appropriate application will process the request and sends the response to WEB SERVER through
Django Project.
py manage.py runserver
(OR)
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/
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.
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.
In the Terminal window of PyCharm IDE, type: py manage.py runserver 8888
cd firstdjangoproject
Note: In the Terminal Window, if already “firstdjangoproject” directory is present then no need to give “cd
firstdjangoproject” command
Note: If py manage.py startapp FirstApp command does not work in Terminal then execute in the
command prompt.
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
So, one directory and six python files will be existed under firstapp directory.
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.
Note: After completing “Function Based views”, we will see “Class Based views”
6. Run server
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:
3) Server and application are ready to receive the request from the user.
http://127.0.0.1:8000/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:
def hello_world_view(request):
return HttpResponse('<h1> This is Response from Django Application designed by the great people of
8pm batch</h1>')
Steps:
1) Start Project
2) Start Application
6) run server
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:
1) Start FourthDjangProject
6) Run Server
1) Start Project
Open PyCharm Window
2) start two applications. One is “greetingapp” and second one is “timeapp”
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.
2) Start “test app” in “Fifth Django Project” (Note: “test app” is the application name)
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
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:
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
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:
2) copy “test app” of “Fifth Django Project” into “Sixth Django Project”
5) Run Server
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.
Ans: The programming code (Python Code) which is related to business requirements. we always write
"business logic" in views.py file
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
Ans: The programming code (SQL Code) which is used to get the data from database. we always place
database logic in Model.
So, views functions of “views.py” file will use Templates (HTML files).
To develop the “Template based projects” in Django, we have to do the following steps:
5) Define view function in “views.py” file i.e. defining business logic in “views.py” file.
7) Run server
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.
template file sends the response to view function i.e. temple_view(request) function view function will
send the response to end-user.
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.
5) Define view function in “views.py” file i.e. defining business logic in “views.py” file.
7) Run server
8) Send the request from the browser.
Views.py
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
(OR)
(OR)
<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
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>
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.
3b)In “testapp” folder, define template file (HTML file i.e. results.html)
5) Define view function (i.e wish() function) in “views.py” file i.e. defining business logic in “views.py” file.
7) Run server
All these steps are same like above. Just type the following code:
views.py
results.html
<style>
body{
background:yellow;
color:blue;
}
</style>
<h1>{{m}}</h1>
urls.py
Output
urls.py
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.
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
urls.py
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),
]
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
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:
i) Add Application
9) Run Server
i) Add Application
{%load static%}
Here load is a keyword and static is a folder name what we created in 4th step.
i) Add Application
Now we are going to write HTML Code regarding “css” static file (i.e. static1.css file)
9) Run Server
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.
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
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.
http://127.0.0.1:8000
Now you can define some CSS styles in “news.css” file as follows:
body{
background:orange;
}
h1{
color:blue;
}
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%}
<h2>EDUCATIONAL NEWS</h2>
And also add <ul> list code:
<ul>
<li>{{Python}}</li>
<li>{{Django}}</li>
</ul>
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
Database is a collection of data which is represented in the form of Tables (Rows and
Columns)
we have to write the database related coding in models.py file by using Model class.
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.
“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.
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.
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)
Open command prompt, next go to Pycharm Projects folder and type django-admin
startproject modelproject1
“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.
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);
“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.
py manage.py migrate
We can see these messages after giving “py manage.py migrate” command
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.
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
Open “admin.py” file which is existed under “testapp” directory, which is existed under
“modelproject1” in Pycharm IDE window.
admin.site.register(Employee)
Next go to browser and press refresh button. Then we will see “Employees” table under
“testapp” as follows:
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.
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.
'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