Django Sessions

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 96

1

What is HTML?
• HTML stands for Hyper Text Markup Language
• HTML is the standard markup language for creating Web pages
• HTML describes the structure of a Web page
• HTML consists of a series of elements(tags)
• HTML elements(tags) tell the browser how to display the content
Structure of the HTML
<html> <! -- it is the root element of an HTML page -->
<head>
<! -- it contains meta data about the HTML doucment.
it defines title, styles of the webpage
scripts( e.g java script) etc.
-->
</head>
<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.
-->
</body>
</html> <! -- end tag of html -->

Note:

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and
display them correctly. A browser does not display the HTML tags, but uses them to determine
how to display the document
2

<html>

<head>
<title> My First Page</title>
</head>
<body>
<h1 > Welcome to Django World </h1>
</body>
</html>
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)
HTML Headings
there are 6 types of heading tags. there are <h1> to <h6> tags.
<h1>: it is used to set highest font size to heading
<h6>: it is used to set least font size to heading
Cascade Style Sheet:
Cascading Style Sheet(CSS) is used to set the style in web page that contain HTML elements.
It sets the background color, font-size, font-family, color, … etc.
There are three types of CSS which are given below:
• Inline CSS

• Internal or Embedded CSS

• External CSS

Inline CSS: Inline CSS contains the CSS property in the body section attached with element is
known as inline CSS. This kind of style is specified within an HTML tag using the style
attribute.
Example:

Eg for inline css


3

<html>
<head>
</head>
<body>
<h1 style = "color:blue;font-size:50px;font-family:Arial;text-align:center;"> Welcome

to Django World </h1>


</body>
</html>
Internal or Embedded CSS: This can be used when a single HTML document must be styled
uniquely. The CSS rule set should be within the HTML file in the head section i.e the CSS is
embedded within the HTML file.
Example:
<html>
<head>
<style>
body
{
background-color:powderblue; <! -- as color we can use red,yellow, grey -->
}
h1{
color:blue;
}
p
{
color:red;
}
</style>
</head>
4

<body>
<h1> Welcome to Django World </h1>
<p> Django is a high level python web application framework </p>
</body>
</html>
note:
to set body background color, we use background-color attribute of css
to set body background image, we use background-image attribute
<style>
body {
  background-image: url('image file name');
}
</style>
background-color: color name
<html>
<head>
<style>
h1
{
color:red;
font-size:100px;
font-family:Serif
text-align: center;
}
body
{
background-image:url('myimage.jpg');
}
</style>
</head>
5

<body>
<h1> Welcome to Django World </h1>
<h1> My first static webpage </h1>
</body>
</html>

External CSS:
• External CSS contains separate CSS file which contains only style property
• with the help of tag attributes (For example class, id, heading, … etc).

2) CSS property written in a separate file with .css extension and should be linked to the
HTML document using link tag.

3) This means that for each element, style can be set only once and that will be applied across
web pages.

Example: The file given below contains CSS property. This file save with .css extension.
Css file:
• save
the file as styles.css
body{
background-color :powderblue;
}
h1 {
color:blue;
}
p{
color: red;
}
<!doctype html>
<head>
<link rel = "stylesheet" href = "styles.css">
</head>
<body>
6

<h1> Welcome to Django World </h1>


<h1>hello</h1>
<p> Django is a highlevel python web application framework </p>
</body>
</html>
The rel attribute specifies the relationship between the current document and the linked
document. Search engines can use this attribute to get more information about a link.
Css fonts:
<!doctype html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 72px;
}
p{
color: red;
font-family: courier;
font-size: 30px;

}
</style>
</head>
<body>
<h1> Welcome to Django World </h1>
<p> Django is a high level python web application framework </p>
</body>
</html>
7

JavaScript

• It is the programming language of the web very easy to learn.

• It is not a compiled language (interpreted language)

• It is an object-based scripting language.

• It is a case-sensitive language.

• The JavaScript Translator is responsible for translating the JavaScript code for the web
browser.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
• Client-side validation,

• Dynamic drop-down menus,

• Displaying date and time,

• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),

• Displaying clocks etc.

There are two ways to write java script code:


1)internal java script
2)external java script
Creating Date and Time Objects

Date objects are created with the new Date() constructor.

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)//date format should be mm//dd//yyyy
ex: 1
<html>
8

<head>
<title>MyPage</title>
</head>
<body>
<h1>Current Date and Time</h1>
<script type="text/javascript">
d=new Date()
document.write(d)
</script>

</body>
</html>
********************************************
ex: 2
<html>
<head>
</head>
<body>
<script type="text/javascript">
var d = new Date(2018, 11, 24, 10, 33, 30);
document.write(d)
</script>
</body>
</html>
**********************************************
<html>
<head>
<title>MyPage</title>
9

</head>
<body>
<h1 style="color:red">My First page</h1>
<h1 style="color:green">current system Date & Time:</h1>
<script type="text/javascript">
d=new Date("4/9/2021");<!-- mm/dd/yyyy format -->
document.write(d);
</script>
</body>
</html>
ex:3

Arithmetic opereators
<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
10

result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
result = ++a;
document.write(result);
document.write(linebreak);
result = --b;
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

ex: 4

<html>
11

<body>
<script type=" text/javascript ">
alert("Masters Technologies")
</script>
</body>
</html>

Java script functions


3)
<html>
<head>
<script type=" text/javascript ">
function f1()
{
alert(" Welcome to Masters Technologies")
}
</script>
</head>
<body>
<p>welcome to Masters Technologies</p>
<form>
<input type="button" value="click" onclick="f1()"/>
</form>
</body>
</html>

Java script in external files


3)
12

We can create java script code in separate file with .js extension.
display.js
function f1()
{
alert("Welcome to Masters technologies")
}
sample.html
<html>
<head>
<script type="text/javascript" src="display.js">
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="f1()" value="click" />
</body>
</html>
<html>
<head>
<title>MyPage</title>
<script type="text/javascript">
function f1(a,b)
{
alert("a+b="+(a+b));
}
</script>
<head>
<body>
13

<input type="button" value="click" onclick="f1(10,20)">


</body>
</html>

To print date and time


<html>
<head>
<script type="text/javascript" >
function f1()
{
document.getElementById("msg1").innerHTML=Date()
}
</script>
</head>
<body>
<p>welcome to Masters Technologies</p>
<form>
<time id="msg1"></time>
<br>
<input type="button" value="click" onclick="f1()"/>
</form>
</body>
14

</html>

Ex: for addition of 2 numbers


<html>
<head>
<script type=" text/javascript ">
function add()
{
var a,b,c;
a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value);
c=a+b
document.getElementById("third").value=c;
}
</script>
</head>
<body>
<p>welcome to Masters Technologies</p>
<form>
<input id= "first">
<input id= "second">
<input id= "third">
<button onclick="add()"> Add</button>
</form>
15

</body>
</html>

Swiping of 2 numbers

<html>
<head>
<script type=" text/javascript ">
function swap()
{
var a,b,c;
a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value);
a=a+b;
b=a-b
a=a-b
document.getElementById("ans1").value=a;
document.getElementById("ans2").value=b;

</script>
</head>
<body>
<p>welcome to Masters Technologies</p>
<form>
a value :<input id= "first">
b value :<input id= "second">
16

after swaping values are<br/>:


<input id= "ans1">
<input id= "ans2">
<button onclick="swap()"> swap</button>
</form>
</body>
</html>

To find reverse of the given number


<html>
<head>
<script type=" text/javascript ">
function reverse()
{
var r,rev=0,n;
n=Number(document.getElementById("input").value);
while(n>0)
{
r=n%10
17

rev=rev*10+r
n=parseInt(n/10)//converting float to int
}
document.getElementById("ans1").value=rev;

</script>
</head>
<body>
<p>welcome to Masters Technologies</p>
<form>
Enter any number :<input id= "input">
Reverse number: <input id= "ans1">
<button onclick="reverse()"> reverse</button>
</form>
</body>
</html>
Java script with phone number validations
phone.js
function phonenumberValidate(){
var Phonenumber=document.getElementById('Phonenumber').value;
var PhonenumberId=document.getElementById('PhonenumberId')
if(Phonenumber.length==0)
{
PhonenumberId.textContent="enter phone number"
PhonenumberId.style.color="green"
}
18

else if(Phonenumber.length==8)
{
PhonenumberId.textContent="valid land phone number"
PhonenumberId.style.color="green"
}
else if(Phonenumber.length==10)
{
PhonenumberId.textContent="valid mobile phone number"
PhonenumberId.style.color="green"
}
else
{
PhonenumberId.textContent="invalid phone number"
PhonenumberId.style.color="red"

}
}

<html>
<head>
<script type="text/javascript" src="phone.js">
</script>
</head>
19

<body>
<form name="f1">
<div>
<label>Phonenumber :</label>
<input type="number" id="Phonenumber" onblur="phonenumberValidate()">
<div id="PhonenumberId"></div>
</div>
</form>
</body>
</html>

Java script with password and confirm password validations


<html>
<head>
<script type="text/javascript">
function validatePassword()
{
var mypassword = document.getElementById('passwordField').value
var regularExpression = /^[A-Z]+[a-z]+[@#$%&!]+[0-9]+$/;
var passwordId=document.getElementById('passwordId');
if(mypassword.length==0)
{
passwordId.textContent="password field should not be empty";
passwordId.style.color="red";
}
else if(!regularExpression.test(mypassword))
{
passwordId.textContent="invalid password must have one uppercase, symbol, digit";
20

passwordId.style.color="red";
}
else if(mypassword.length<6 || mypassword.length>16)
{
passwordId.textContent="minlen:6 maxlen:16"
passwordId.style.color="red";
}
else
{
passwordId.textContent="password is valid";
passwordId.style.color="green";
}
}
function confirmPasswordValidate(inputTxt)
{
var Password = document.getElementById('passwordField').value;
var confirmPasswordField=document.getElementById('confirmPasswordField').value;
var confirmPasswordId=document.getElementById('confirmPasswordId');
if(confirmPasswordField.length==0)
{
confirmPasswordId.textContent="confirm passwrod field should not be empty";
confirmPasswordId.style.color="red";
}
else if(Password!=confirmPasswordField )
{
confirmPasswordId.textContent="password dint matched";
confirmPasswordId.style.color="red";
}
21

else
{
confirmPasswordId.textContent="password matched";
confirmPasswordId.style.color="green";
}
}
</script>
</head>
<body>
<form >
<div>
<label>password:</label>
<input type="password" id="passwordField" Onblur="validatePassword()"/>
</div>

<div >
<div id="passwordId"></div>
</div>

<div >
<label>ConfirmPassword :</label>
<input type="password" id='confirmPasswordField' name="a5" class="form-
control" onblur='confirmPasswordValidate()' />
<div id="confirmPasswordId"></div>
</div>
</form>
</body>
</html>
22

Java script with mail ID validations


<html>
<head>
<script>
function emailValidation()
{
var email=document.getElementById('emailField').value;
var emailId=document.getElementById('emailId')
var emailRegEx=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]
{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(email.length==0)
{
emailId.textContent="mailId should not be empty";
emailId.style.color="red";
}
else if(emailRegEx.test(email))
{
emailId.textContent="valid mailId";
emailId.style.color="green";
}
else
{
emailId.textContent="invalid mailId: it must have @ symbol and should be end
with .com or co.in or .in ...etc";
emailId.style.color="red";
}
}
</script>
<body>
23

<form name="f1" action="">


<div>
<label>Email_id :</label>
<input type="text" id='emailField' onblur='emailValidation()' />
</div>

<div >
<div id="emailId"></div>
</div>
</form>
</body>
</head>
</html>

captcha example
=====================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Captcha Validation in JavaScript</title>
<style>
form{
width:500px;
margin:10px auto;
24

border-radius: 10px;
border: 1px solid grey;
padding: 20px;
}
label{
display:block;
font-size: 20px;
margin:10px 0px;
font-weight: bold;
}
input{
width:450px;
padding: 8px;
border-radius: 8px;
font-size:16px;
}
button{
width:450px;
margin: 10px 0px;
border-radius: 8px;
font-size:16px;
cursor:pointer;
height:35px;
padding:8px;
background-color: rgb(213, 219, 224);
}
#captchaid{
font-size:20px;
25

color:rgb(10, 10, 10);


font-weight: bold;
background-color: rgb(177, 174, 174);
padding:8px;
width : 200px;
border-radius:8px;
}
</style>
<script>
function otpgenerator(){
data
="0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
strlenght=data.length;
otp = "";
for (i=0; i<6; i++){
otp +=data[Math.floor(Math.random()*strlenght)];
}
document.getElementById("captchaid").textContent = otp;
}
</script>
</head>
<body onload="otpgenerator();">
<form action="" method="post" onsubmit="captcha_validation();">
<h3>Form Captcha Implementation Using JavaScript !</h3>
<label for="">Email :</label>
<input type="text" name="email" id="email" placeholder="Email">
<label for="">Password :</label>
<input type="password" name="password" id="password" placeholder="Password">
<label for="">Captcha :</label>
26

<label for="" id="captchaid" name="captchid"></label>


<input type="text" name="captcha" id="captcha" placeholder="Captcha">
<button type="submit">Submit</button>
</form>
<script>
function captcha_validation(){
var captchaid = document.getElementById("captchaid").textContent;
var captcha = document.getElementById("captcha").value;
if (captcha.length == 0){
alert("Fill captcha then submit ..!");
document.getElementById("captcha").focus();
return false;
}
else if (captchaid != captcha){
alert("Entered captcha does not matched try again..!");
document.getElementById("captcha").focus();
return false;
}
else{
alert("Captcha validation successfull..!");
return true;
}
return false;
}
</script>
</body>
</html>
Math.random(): The random() method returns a random number from 0
(inclusive) and 1 (exclusive).
27

Math.floor(): function returns the largest integer less than or equal to a given number.
ex:
Math.floor(5.95));
// expected output: 5
Math.floor(5);
// expected output: 5
var x = Math.floor((Math.random() * 10)+1);
generates number b/w 1 and 10

Radio and CheckBox:


------------------------
<html>
<head>
<script>
function checkButton1() {
if(document.getElementById('summer').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("summer").value
+ " radio button is checked";
}
else if(document.getElementById('winter').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("winter").value
+ " radio button is checked";
}
else if(document.getElementById('rainy').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("rainy").value
28

+ " radio button is checked";


}
else if(document.getElementById('autumn').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("autumn").value
+ " radio button is checked";
}
else {
document.getElementById("error").innerHTML
= "You have not selected any season";
}
}

function checkButton() {
var getSelectedValue = document.querySelector(
'input[name="season"]:checked');

if(getSelectedValue != null) {
document.getElementById("disp").innerHTML
= getSelectedValue.value
+ " season is selected";
}
else {
document.getElementById("error").innerHTML
= "*You have not selected any season";
}
}
</script>
29

</head>
<body>
<br><b> Choose your favroite season: </b><br>
<input type="radio" name="season" id="summer" value="Summer"> Summer

<br>
<input type="radio" name="season" id="winter" value="Winter"> Winter <br>
<input type="radio" name="season" id="rainy" value="Rainy"> Rainy <br>
<input type="radio" name="season" id="autumn" value="Autumn"> Autumn
<br><br>

<button type="button" onclick="checkButton1()/checkButton()"> Submit </button>

<h3 id="disp" style= "color:green"> </h3>


<h4 id="error" style= "color:red"> </h4>
</body>

</html>

Select:
======
The <select> element is used to create a drop-down list.

The <select> element is most often used in a form, to collect user input.

The name attribute is needed to reference the form data after the form is submitted (if you omit
the name attribute, no data from the drop-down list will be submitted).

The id attribute is needed to associate the drop-down list with a label.


30

The <option> tags inside the <select> element define the available options in the drop-down list.

Tip: Always add the <label> tag for best accessibility practices!

1) Using the Option constructor and add() method


First, use the Option constructor to create a new option with the specified option text and value:

let newOption = new Option('Option Text','Option Value');


Code language: JavaScript (javascript)
Then, call the add() method of the select box object:

selectBox.add(newOption,undefined);
Code language: JavaScript (javascript)
The add() method accepts two arguments. The first argument is the new option and the second
one is an existing option.
In this example, we pass undefined as the second argument, the method adds the new option to
the end of the options list.
<html>
<head>
<script type="text/javascript">
function f1()
{
state=document.getElementById("state").value;
city=document.getElementById("city");
while(city.options.length>1)
city.remove(1);
if(state=='AndhraPradesh')
{
31

city.add(new Option("Vijaywada","Vijaywada"),undefined);
city.add(new Option("Vizag","Vizag"),undefined);
city.add(new Option("Kakinada","Kakinada"),undefined);
}
else
{
city.add(new Option("Hyderabad","Hyderabad"),undefined);
city.add(new Option("Secunderabad","Secunderabad"),undefined);
city.add(new Option("Wrangal","Wrangal"),undefined);
}
}
</script>
</head>
<body>
<form>
<select id="state" onchange="f1()">
<option disabled selected>--Choose Country--</option>
<option>AndhraPradesh</option>
<option>Telagana</option>
</select>
<select id="city">
<option disabled selected>--Choose City--</option>
</select>
</form>
</body>
</html>
32

<html>
<head>
<script type="text/javascript">
function f1()
{
uname=document.getElementById("uname").value;
email=document.getElementById("uemail").value;
age=document.getElementById("age").value;
country=document.getElementById("country").value;
pwd=document.getElementById("pass").value;
resume=document.getElementById("res").value;
hobbie1=document.getElementById("hobbie1");
hobbie2=document.getElementById("hobbie2");
if(hobbie1.checked==true && hobbie2.checked==true)
hobbie="Cricket,Football";
else if(hobbie1.checked==true)

hobbie="Cricket";

else if(hobbie2.checked==true)
hobbie="Football";
if(document.getElementById("female").checked==true)
gender=document.getElementById("female").value;
else
gender=document.getElementById("male").value;
city=document.getElementById("city").value;
addr=document.getElementById("addr").value;
op=document.getElementById("opt");
33

op.innerHTML="username:"+uname+"</br>"+"Email:"+email

+"</br>"+"age:"+age+"</br>"+"country:"+country

+"</br>"+"password:"+pwd+"</br>"+
"resume:"+resume+"</br>"+"hobbie:"+hobbie+"</br>"+"gender:"+gender

+"</br>"+"city:"+city+"</br>"
+"address:"+addr+"</br>";
}
</script>
</head>
<body>
<form >
<table>
<tr>
<td>
<label for="uname">Name</label>
</td>
<td>
<input type="text" id="uname" name="username">
</td>
</tr>
<tr>
<td>
<label for="uemail">Email</label>
</td>
<td>
<input type="text" id="uemail" >
34

<button type="button">Check</button>
</td>
</tr>
<tr>
<td>
<label for="age">Age</label>
</td>
<td>
<input type="text" id="age" size="2" maxlength="2">
</td>
</tr>
<tr>
<td>
<label>Country</label>
</td>
<td>
<input type="text" id="country" >
</td>
</tr>
<tr>
<td>
<label for="pass">Password</label>
</td>
<td>
<input type="password" id="pass">
</td>
</tr>
<tr>
35

<td>
<label for="res">Resume</label>
</td>
<td>
<input type="file" id="res">
</td>
</tr>
<tr>
<td>
<label>Hobbies</label>
</td>
<td>
<label>
<input type="checkbox" id ="hobbie1" checked> Cricket
</label>
<label>
<input type="checkbox" id ="hobbie2"> Football
</label>
</td>
</tr>
<tr>
<td>
<label>Gender</label>
</td>
<td>
<label for="gender">
<input type="radio" name="gender" value="F" id="female">

Female</label>
36

<label>
<input value="M" name="gender" type="radio" id="male">

Male</label>
</td>
</tr>
<tr>
<td>
<label for="city">City</label>
</td>
<td>
<select id="city" >
<option disabled selected>--Choose City--</option>
<optgroup label="Metros">
<option>New Delhi</option>
<option>Hyderabad</option>
<option>Channai</option>
<option>Kolkata</option>
</optgroup>
<optgroup label="Others">
<option>Noida</option>
<option>Gurgram</option>
<option>Faridabad</option>
<option>Gaziabad</option>
</optgroup>
</select>
</td>
</tr>
<tr>
37

<td>
<label>Address</label>
</td>
<td>
<textarea rows="4" cols="40" id="addr"></textarea>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="f1()">
<input type="reset">
</td>
</tr>
</table>
<output id="opt"></output>
</form>
</body>
</html>

Django
• Started by Adrian Holovaty and Simon Willison in the year 2003

• It released July 2005

• Django is now an open source web framework with contributors across the world.

• It enables to build rich web applications with minimal time and effort.

• To develop web based applications using django framework, we need some


38

language. Python is best language for developing web applications by using


Django. since it is written in Python.

Advantages of Django:

Loosely Coupled: Django makes each element independent of the others.

Less Coding: Less code, so application development is very easy and Quick.

Don't Repeat Yourself (DRY): allows developer to reuse modules of one project in another
project.

Object-Relational Mapping (ORM) Support: Django provides a bridge between the data
model and the database engine, and supports a large set of database systems including MySQL,
Oracle, Postgre sql, etc. Django also supports NoSQL databases like MongoDB and google app
engine.

Multilingual Support: Django supports multilingual websites through its built-in


internationalization system. So you can develop your website, which would support multiple
languages.

Framework Support: Django has built-in support for Ajax(Asynchronous JavaScript And
XML), Caching and various other frameworks.

note:  AJAX is a new technique for creating better, faster, and more interactive web applications
with the help of XML, HTML, CSS, and Java Script.

Administration GUI: Django provides a nice ready-to-use user interface for administrative
activities.

Like most modern frameworks, Django supports the MVC pattern(Model-View-Controller), and
Model-View-Template (MVT) pattern.
Django follows a model-view-controller design(MVC)
MVC is specially designed for web application development.
MVC separates
data(model)
user interface(view)
data handling logic(controller)

designers can work on view without worrying about data storage or management.
Developers concentrate on logic of data handling without worrying about presentation.
They can be changed without affecting others.
39

Django - Environment

Installing, Required Software


Our development environment consists of Python, Django, and a database system.
we can install any database system like Mysql, Oracle, Postgre, Sqlite ..etc. Django
project comes with default database Sqlite3.

Installing Python

Django is written in Python, so the first step in setting up our development


environment with Python installation. Python is available for a variety of operating
systems. we know the steps to install python.

Installing Django on Windows

Installing Django is very easy, but it depends on your operating system. Since Python is a
platform independent language, Django has one package that works everywhere regardless of
your operating system.

go to command prompt type

pip install Django==3.1.5

c:\>django-admin.py --version

Installing a Database System

While Django does not require a database for it to function. Django supports several database
engines: MySQL, PostgreSQL, MS SQL Server, Oracle, and SQLite. Interestingly however, you
40

only need to learn one API in order to use any of these database systems. This is possibly
because of Django's database layer, which abstracts access to the database system.

If you have Python 2.5 or higher, you won't need to install anything, since Python2.5 comes with
the SQLite database management system contained in a module named sqlite3. Unlike client-
server database systems, it stores the database in a single file, which makes it ideal for our
development environment. Of course you are free to use your preferred database management
system. We can tell Django what database system to use by editing a configuration file. It is also
worth noting that if you want to use MySQL, you will need to install MySQLdb(MySQL driver
for Python)with the following command.

c:\.....>pip install pymysql

or
c:\...> pip install mysql-connector-python
or
c:\......>pip install mysqlclient

Architecture of Django
41

Architecture of the Django(MVT):

• Whenever end user sends the URL request, which is received by the URL Dispatcher.
• URL dispatcher is a program which is used to compare requested URL with list of urls
present urls.py(it is created by django automatically at the time of creating project), if
there is matching url, the function which is configured with the url is executed. Otherwise
result will be runtime error.
• Every url pattern of urls.py file should be registered with a view function/view classs .
• A view is a python function or class which receives client request and process that
request and sends response to the client.
• All views functions (or) view classes ,should be defined in the views.py file
42

• The views.py file will be automatically created at the time of creating an app’s
• At the time of processing the client request ,we can communicate With database through
the model
• A model is a python class which represents tables in database.
• In order to store the data into db or retrieve data from db, then we need to create/write a
model query.
• The model queries are similar to the SQL queries and we can write model queries by
using API’s. the model queries are database independent queries.
• All model classes are created in models.py file.
• The models.py class will be automatically created at the time of creating an app’s.
• After processing the client request by the view, view will transfer the result to the
template (template is text file which contains html + python code). Template will be
rendered into html which is forwarded to the browser for presentation.

Django - Creating a Project

In Django, every web app you want to create is called a project; and a project is a sum of
applications. An application is a set of code files relying on the MVT pattern. As example let's
say we want to build a website, the website is our project and, the forum, news, contact engine
are applications. This structure makes it easier to move an application between projects since
every application is independent.

Create a new Project using pycharm IDE:


43

click on NewProject button

1. Enter project name(select any path)

Ex : DateProject

2. select python interpreter


ex: Python 3.9
44

3. click on Create button

The Project Structure

The “DateProject” folder is just your project container, it actually contains two elements :
manage.py: This file interact with your project via command line . To get a full list of command
accessible via manage.py you can use the code.

$ python manage.py help

The “DateProject” subfolder: This folder is the actual python package of your project. It
contains four files:

__init__.py : Just for python, treat this folder as package.


settings.py : As the name indicates, your project settings.
urls.py : All links of your project and the functions.
wsgi.py : If you need to deploy your project over WSGI.

Setting Up Your Project

Your project is set up in the subfolder DateProject/settings.py. Following are some important
options you might need to set.
DEBUG = True
45

Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a
live project. However, this has to be set to ‘True’ if you want the Django light server to serve
static files. Do it only in the development mode.

The Development Server:

Django includes a built-in, lightweight Web server you can use while developing your site.
We’ve included this server so you can develop your site rapidly, without having to deal with
configuring your production Web server (e.g., Apache) until you’re ready for production. This
development server watches your code for changes and automatically reloads, helping you make
many rapid changes to your project without needing to restart anything.
Now that your project is created and configured make sure it's working
Change into the mysite directory, and run the command

c:\......>python manage.py runserver

You’ll see something like this:


Validating models...
0 errors found.
Django version 1.0, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Although the development server is extremely nice for, well, development. The development
server can handle only a single request at a time reliably.

Changing the Host or the Port

By default, the runserver command starts the development server on port 8000, listening only for
local connections. If you want to change the server’s port, pass it as a command-line argument:

8080.

You can also change the IP address that the server listens on. This is especially helpful if you’d
like to share a development site with other developers. The following:

python manage.py runserver 0.0.0.0:8080

will make Django listen on any network interface, thus allowing other computers to connect to
the
development server. Now that the server’s running, visit http://127.0.0.1:8080/ with your Web
browser.

You’ll see a “Welcome to Django” page


shaded a pleasant pastel blue. It worked!
46

YOUR FIRST APP

Note : To work with Django framework , you need not create apps at all, for example the view
functions can be created without any app. But if you want to use Django’s database layer
(models), you must create a Django app. Models must live within apps. to start writing our
models, we’ll need to create a new app Within the DateProject project directory you created.

python manage.py startapp DateApp

This command does not produce any output, but it does create a DateApp directory within the
DateProject directory.

mysite/
__init__.py
models.py
views.py

These files will contain the models and views for this app. Models.py and views.py files are
empty, except for an import in models.py. This is the blank slate for your Django app.

Let’s create a Web page that displays the current date and time. To create this page, we’ll write a
view function. A view function, is simply a Python function that takes a HttpRequest and returns
a HttpResponse.

MAPPING URLS TO VIEWS

we tell django to use the bove code by configuring URLconfs. A URLconf is like a table of
contents for your Django Web site. Basically, it’s a mapping between URL patterns and the view
functions that should be called for those URL patterns.

To configure view(python function)with URLconf file

open urls.py file present in DateApp subfolder present in project folder which is created

from django.contrib import admin


from django.urls import path,re_path
from myapp.views import current_datetime
urlpatterns = [
path('admin/', admin.site.urls),path("dt/",current_datetime),]
47

views.py:

from django.http import HttpResponse


import datetime

def current_datetime(request):
dt = datetime.datetime.now()
html = "<html><body>current time is %s</body></html>"%(dt)
return HttpResponse(html)

We made two changes here. First, we imported the current_datetime view from its module
(DateApp/views.py. Next, we added the line path(r'dt/',current_datetime),. This line is referred to
as a URLpattern—it’s a Python list in which the first element is a simple regular expression and
the second element is the view function to use for that pattern.
With the configuration, we just told Django that any request to the URL http://localhost:8000/dt/
should be handled by the current_datetime view function.

Note:

• Note that, in this example, we passed the current_datetime view function as an object without
calling the function. This is a key feature of Python (and other dynamic languages): functions are
first-class objects, which means you can pass them around just like any other variables.

The server is running at the address http://127.0.0.1:8000/, so open up a Web browser and
go to http://127.0.0.1:8000/dt/. You should see the output of your Django view.

URLCONFS AND LOOSE COUPLING


If two pieces of code are loosely coupled, then changes made to one of the pieces will have little
or no effect on the other.

In a Django Web application, the URL definitions and the view functions they call are loosely
coupled. URL mapping of the view function and view definition both reside in two separate
places. This lets a developer switch out one piece without affecting the other.

For example, consider the view function we wrote earlier, which displays the current date and
time. If we change the URL (like from /time/ to /currenttime/),we need not worry about the
underlying implementation of the function. Similarly, if we wanted to change the view
function(altering its logic ) could do that without affecting the URL to which the function is
bound.

YOUR SECOND VIEW: DYNAMIC URLS


48

In our first view example, the contents of the page the current date/time were dynamic, but the
URL (/time/) was static.

Let’s create a second view that displays the current date and time offset by a certain number of
hours. For example the page /time/plus/(1)/ displays the date/time one hour into the future, the
page /time/plus/(2)/ displays the date/time two hours into the future, the page /time/plus/(3)/
displays the date/time three hours into the future, and so on.
urlpatterns = [
url(r'^admin/', admin.site.urls),url(r'^time/$', current_datetime),
url(r'^time/plus/(1)/$',one_hour_ahead),url(r'^time/plus/(2)/$', two_hours_ahead),
........
..........
.......
]
This URLpattern will match any URL such as /time/plus/(2)/, /time/plus/(25)/, or even
/time/plus/
(100000000000)/.
insted of writing those many number of url mappings ,we can use regular expressions to
overcome the above problem. so, we can use a single view function for any arbitrary hour offset.
We do this by placing parentheses around the data in the URLpattern that we want to save. In the
case of our example, we want to save whatever number was entered in the URL,
so let’s put parentheses around the \d{1,2}:
url(r'^time/plus/(\d{1,2})/$', hours_ahead),

from django.conf.urls.defaults import *


from mysite.views import current_datetime, hours_ahead
urlpatterns =[path('admin/', admin.site.urls),
path(r'^time/$', current_datetime),url(r'^time/plus/(\d{1,2})/$', hours_ahead), ]
or
re_path(r"^time/plus/(\d{1,2})/$",hours_ahead)

hours_ahead is very similar to the current_datetime view we wrote earlier, with a key difference:
it takes an extra argument, the number of hours of offset. Add this to views.py:

from django.http import HttpResponse


import datetime
def hours_ahead(request, offset):
offset = int(offset)
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" %(offset, dt)
return HttpResponse(html)
we calculate the current time plus a time offset of offset hours, storing the result in dt. The
datetime.timedelta function requires the hours parameter to be an integer.
To use the above urls visit
http://127.0.0.1:8000/time/plus/3/ => it works.
49

Then http://127.0.0.1:8000/time/plus/24/.

Finally, visit http://127.0.0.1:8000/time/ plus/100/=>404 error

to verify that the pattern in your URLconf only accepts one- or two-digit numbers; Django
should display a “Page not found”.

Templates:
TEMPLATE SYSTEM BASICS
A Django template is a string of text that is used to separate the presentation logic form the
business logic. A template defines placeholders and various bits of basic logic (i.e., template
tags) that regulate how the document should be displayed.
The template languages are:
• DTL Django template language
• Jinja2 (it doesn’t support 1.8 below)

Project1
-----------app1
--------views.py
--------project1
---------settings.py
---------urls.py
---------template
------Home.html
-------News.html
-------Contact.html
---------manage.py
50

Views.py:
The Render Function
This function takes three parameters −
• Request− The initial request.
• The path to the template− This is the path relative to the TEMPLATE_DIRS option in
the project settings.py variables.
• Dictionary of parameters− A dictionary that contains all variables needed in the template.
This variable can be created or you can use locals() to pass all local variable declared in
the view.

Urls.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from app1.views import welcome
urlpatterns = [
path('admin/', admin.site.urls),url(r'^welcome/',welcome)]

from django.shortcuts import render


# Create your views here.
def welcome(request):
return render(request,'welcome.html')
create a ‘template’ folder in project directory
welcome.html
<html>
<body>
Welcome to Masters Technologies
</body>
</html>
Save it in template folder
Go to Setting.py, configure application name in INSTALLED_APPS LIST as follows
INSTALLED_APPS = [
'django.contrib.admin',
51

'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
]
• Python manage.py runserver

Django Templates:
• It is a text file which contains static and dynamic contents.
• Any text that is surrounded by “{{ }}” is known as variable
syntax : {{variable name}}
• Any text that is surrounded by {% template tag %} is known as template tag
• The template engine is a software, which, loads and render a template into markup
language.
• Each template engine defines a language to create templates.
• In django the template engine provides 2 languages.
• 1)DTL(Django template language):-supported by all versions of django
• 2)jinja2(it is supported from djnago1.8version onwards)
Template tags:

if tag:
syntax:
{% if condition %}
--------------
---------------
{% endif %}
52

else tag

syntax:
{% if condition %}
--------------
---------------

{% else %}
--------------
--------------

{% endif %}

If …elif …. tag:=

syntax:
{% if condition1 %}
--------------
---------------

{% elif condition2 %}
--------------
--------------
{% else %}
--------------
--------------
{% endif %}
53

Comment:

{#--------------------#}single line comment

{% comment %}
---------------
---------------
{% endcomment %}

For loop

{% for variable in collection object %}


-------------------
-------------------
{% endfor %}

Ex:
54

TemplateProject
---------------static
---------bootstrap
------css
------bootstrap.min.css
------
------js
---------
---------
---------css
---------style.css
--------images
-------python-icon-10
----------------template
------------Base.html
------------Home.html
------------Contact.html
------------News.html
-------------navbar.html
-------------------NewsApp
-----------Views.py
-------------------TemplateProject
-------------urls.py
-------------stettings.py
55

1)create a new folder in your project with the name ‘static’. to the static folder, we can add
styles, images….etc.
2)create a sub folder to the ‘static’ folder with the name ‘css’
3)add file style.css file to the css folder
Note: we have to tell to django that we have static folder.
to tell that, goto base.html, add following statement
{% load static %}

to create a link b/w html doc and sytele.css fil, go to base.html, add following statement
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">

to add static folder path to the project path, go to settings.py, add following statement
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
to set image as page background, go to base.html, set image as follows
<body style="background-image: url('{% static "images/python-icon-10.jpg" %}');" >

base.html
------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
{% include 'navbar.html' %}
{% load static %}
56

<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">


<link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
</head>
<body style="background-image: url('{% static "images/python-icon-10.jpg" %}');" >
{% block body %}
{% endblock %}
</body>
</html>

home.html
------------
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block body %}
<h1>Home Page</h1>
<p>Welcome To MySite</p>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>

<button type="button" class="btn btn-link">Link</button>


{% endblock %}
57

Contact.html
---------------
{% extends 'base.html' %}
{% block title %}Contact{% endblock %}
{% block body %}
<h1>Contact Page</h1>
<p>you can Contact us by this form</p>
{% endblock %}

News.html:
-------------
{% extends 'base.html' %}
{% block title %}News{% endblock %}
{% block body %}
<h1>News Page</h1>
<p>This is new Content</p>
{{ list }}
{% for lang in list %}
<ul>
<li>{{ lang }}</li>
</ul>
{% endfor %}
{% if mynum == 50 %}
<h2> condition is true</h2>
{% else %}
<h2>condition is false</h2>
{% endif %}
{% endblock %}
58

navbar.html
=========
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'news' %}">News</a></li>
<li><a href="{% url 'contact' %}">Contact</a></li>
</ul>
</nav>

Views.html
=========
from django.shortcuts import render

# Create your views here.


def Home(request):
return render(request,"Home.html")
def News(request):
context = {"list":["c","c++","java","python","scala","hadoop"],"mynum":50}
return render(request,"News.html",context)
def Contact(request):
return render(request,"Contact.html")
59

urls.py
-------
from django.contrib import admin
from django.urls import path
from NewsApp.views import News,Contact,Home
urlpatterns = [
path('admin/', admin.site.urls), path("", Home, name="home"), path("news/", News,
name="news"),path("contact/", Contact, name="contact"),
]

Template Filters
• Django template filters are used to modify the value of variable before they are
rendered as html code.
• To use a filter pipi character followed after by variable name
Syntax {{variable | filter-name}}
1)to convert upper case string into into lower case
Syntax: {{variable|lower}}
Ex: {{“Master Technologies “|lower}} o/p: master technologies
2)upper to convert all the character into lower case
Syntax: {{variable|upper}}
Ex: {{“Master Technologies”|upper}} o/p: MASTER TECHNOLOGIES
3)capfirst to convert first word first character into upper case
Syntax: {{variable| capfirst }}
Ex: {{“master technologies”| capfirst }} o/p: Master technologies

4)title –to return each and every word first character in capital case
Syntax: {{variable| title}}
Ex: {{“ master technologies” | title}} o/p: Master Technologies
5) length: to return the number of characters in a variable
Syntax: {{variable name | length}}
60

Ex: {{‘satya’ | length}}


o/p: 5
6) truncate words: the truncate words filter, truncate (shortens) a string after a certain
number of word.
After truncating the string, it appends 3 dots (…) to the end of the truncated string is
called Ellipsis (…)
Syntax: {{variable name | truncatewords: “number of words”}}
Ex:
{{“Django is a high level python web application framework"| truncatewords: “5”}}
o/p: “Django is a high level...”
7) truncatechars: truncating a character
Syntax: {{variable name | truncatechars: “number of characters”}}
Ex: {{“Django is a high level python web application framework"| truncatechars:
“5”}}
o/p: “Djang…”

datetime(object)
dt=datetime.date.today()
print(dt)
datetime.date(2021, 12, 18)
dt.year
2021
print(dt.month)
12
print(dt.day)
18

dt=datetime.datetime.now()
print(dt)
61

datetime.datetime(2021, 12, 18, 17, 30, 14, 357655)


print(dt.year)
2021
print(dt.month)
12
print(dt.day)
18
print(dt.hour)
17
print(dt.minute)
30
print(dt.second)
22
print(dt.weekday())
5
print(dt.isoweekday())
6
print(dt.isocalendar())
datetime.IsoCalendarDate(year=2021, week=50, weekday=6)
62

Special characters
d => to print a day of month using two-digit numbers. (01 to 31 Ex: 30/02/28)o/p:30
D => to print a day of week using 3 letters.
m => to print month using 2 digit number.
01
.
.
.
12
M to print month using 3 letters.
Jan – January
.
.
.
Dec – December
i => to print time in minutes
h => to print time in hours in 12 hours format (00 to 12)
H => to print time in hours in 24 hours format (00 to 23)
s => to print time in seconds.
a => to print a.m or p.m
Y => to print a year in 4 digits.
Ex: now= datetime.datetime.now
{{now | date: “D d M Y”}}
O/P: Tue 14 Aug 2018

from django.shortcuts import render


from django.views.generic import View
import datetime
63

class Welcome(View):
def get(self,request):
now = datetime.datetime.today()
return render(request,"filters.html",{'now': now, 'day': now.day, "month": now.month,
'year': now.year})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color:red">
lower filter o/p: {{"MASTERS TECHNOLOGIES"|lower}}<br>
upper filter o/p: {{"masters technologies"|upper}}<br>
cap filter o/p: {{"master technologies"|capfirst }}<br>
title filter o/p: {{"master technologies"|title }}<br>
length filter o/p: {{"satya" | length}}<br>
trucatewords filter o/p: {{"Django is a high level python web application framework"|
truncatewords:"5"}}<br>
trucatechars filter o/p: {{"Django is a high level python web application framework"|
truncatechars:"5"}}<br>
date is:{{now|date:"D d M Y"}}<br>
day is:{{day}}<br>
month is:{{ month }}<br>
year is:{{ year }}<br>
week day is:{{ now|date:"D"}}
</h1>
</body>
64

</html>

HTTP:
• It is a web protocol
• It is hyper transfer protocol
• It is designed to enable communication between client and server.
• HttpRequest:
• We can use request object to get end user provided information.
• HttpResponse:
• To prepare and send response to end user
• Http Methods:
• GET ()
• POST ()
• PUT ()
• DELETE ()
• OPTION ()
• HEAD ()
• TRACE ()
• CONNECT ()
• MOVE ()
10.LOCK ()
NOTE:
The most commonly used http methods for a request between client and server is GET ()
and POST ()
How to send GET () request:
• When we submit “url” in address bar of the browser
• When we click on “hyperlinks”
• When we submit the “form” without method attribute or method attribute with value
get
65

How to send POST () request:


• When we Submit the “form” with method attribute value post.

Difference between GET () and POST () :


GET () POST ()
• It is used to send small 1. It is used to post the
amount of data to the unlimited data to server
server side application side application.
2. This request can be made
• GET() request can be only on submitting “forms”.
made by typing “URL” or by
clicking on “hyperlinks”
or submitting “forms”. 3. This request, we have to
• This request is a default specify explicitly.
request.
• Data is appended to query 4. Data is not appended to
string of “url”. the query string of “url”.
• No security for data 5. POST () method provides
• GET () method is not security.
suitable for uploading 6. It is suitable for uploading
the files. the files
• It is not suitable for 7. It is suitable for submitting
submitting sensitive sensitive information
information.
Example for get, post methods:
• If user submits the get request, GET dictionary object will be created in the ‘request’
object, which contains user inputs in the form of key value pairs.
• We can read the data in the view function/ view class by using following syntax:
66

variable name= request.GET [“key”]


• If user submits the post request, POST dictionary object will be created in the ‘request’
object, which contains user inputs in
the form of key value pairs.
• and we can read that data in the view fun/view class by using following syntax:
variable= request. POST [“key”]
Note: The data which is submitted by the end user will be taken in the form of string.

Ex for Templates:

Model
A model is a python class which represents a table in the database.
Each attribute of the model class, represents column of the table.
We can create model object by creating new subclass from the django.db.models.Model base
class.
We can specify the type of attribute by using classes present in django.db.models classname. We
can also specify the size of attribute and constraint of the attribute at the time of creating table.
If the model class does not contain any primary key attribute, then internally django framework
adds primary key column with name ID or PK.
All the model classes should be implemented models.py file, which is created automatically at
the time of creating application.
Makemigrations
makemigrations basically generates the SQL commands for preinstalled apps (which can be
viewed in installed apps in settings.py) and your newly created apps’ model which you add in
installed apps. It does not execute those commands in your database file. So tables are not
created after makemigrations.
67

Migrate
migrate executes those SQL commands in the database file. So after executing migrate all the
tables of your installed apps are created in your database file. We can store the data into db tables
and we can get the data from db tables by using model queries .
Model queries are database independent.
To create user defined model class , create a new class that should be derived from
django.db.model.Model class.

Django provides fields to store different types of data. They are


1)CharField:
This is used for storing a small to medium sized strings.
It acts as base class for other string fields.
It does not provide any validations
2)DateField
Used to store date
It is like datetime.date object
It provides validations
3)DateTimeField
It is used to store date and time
It is like datetime.datetime instance
It provides validations.
EmailField:
It is CharFiled to store Email address.
It provides email validations.
URLFiled:
It is CharFiled used to store URL
It provides validations
It checks given URL is valid or not valid.
TextField
68

Used to store large amount of text


This field does not provide any validations
BooleanField
Used to store True of False
To check whether given value is Boolean or not
IntegerField:
Used to store integer values
It checks given value is number or not
DecimalField
Used to store decimal number
ForeignKey
Used to define one-to-many relationships
ManyToManyField
Used to define many-to-many relationships
OneToOneFiled
Used to define one-to-one relationsships.
AutoField
It is a special type of IntegerFiled that automatically increments.

Model Field Attributes


max_length: to define length of attribute
If max-length is not specified Django will use a default length of 50.
help-text: provides a text filed label for html forms
null: if true django will store NULL in the field .otherwise will store empty string(default value
is false) .
blank:
if true, the field is allows blank value. By default it is false, which means django’s form
validation will force you to enter value.
primary_key:
69

If true ,set the current filed as the primary key for the model
Note : if no filed is specified as primary key the django will automatically add a filed with name
id.
unique:
if true this field must be unique throughout the table
auto_now:
automatically set the filed to now every time the object is saved.
Ex: it is useful for ‘last-modified’ time stamps
auto_now_add:
automatically set the filed to now when the object is first created
useful for creation of timestamps.
Model relationships:
1)one-to-one relationship
2)one-many (or) many-one relationship
3)many-many relationship
One-to-one relationship:
In this case, any one record of one table can have relationship with only one record of other table
We can create one-to-one relationship we use
Django.db.model.OneToOneFiled
Ex: class profile(model.Model):
user = models.OneToOneFiled(User,on_delete=model.CASCADE)
on_delete=model.CASCADE
by default, without deleting child table record we can’t delete the master table record. whenever
we apply on_delete CASCADE option, if we delete master table record then automatically it’s
associated child table record is also deleted, after deleting the records we can apply the model
queries to those tables.
EmployeeDetails Project
-----------------------
EmpDetails
-----------emp
70

--------views.py
---------models.py
--------EmpDetails
---------settings.py
---------urls.py
---------template
------showemp.html
---------manage.py

in the above project:


create model in models.py
from django.db import models

class EmpMaster(models.Model):

eid = models.IntegerField(primary_key=True)

ename = models.CharField(max_length=50)

salary = models.FloatField()

gender = models.CharField(max_length=1)

deptno = models.IntegerField()

def __str__(self):

return "%s,%s,%s,%s,%s" % (str(self.eid), self.ename, str(self.salary), self.gender, self.deptno)

register your app in settings.py as follows

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',
71

'emp'

create a connection b/w django and mysqldatabase in settings.py as follows

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'empdetails',

'USER': 'root',

'PASSWORD': 'root',

'HOST': 'localhost',

'PORT': 3306,

create sql Queries for the model which we have created with following command at pycharm terminal

C:\Users\satya\Desktop\DjangoBatch12PM\EmpDetails>py manage.py makemigrationsto

to run sql queries which are created by the makemigrations command

C:\Users\satya\Desktop\DjangoBatch12PM\EmpDetails>py manage.py migrage emp

to run model queries at django terminal

C:\Users\satya\Desktop\DjangoBatch12PM\EmpDetails>py manage.py shell

Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on

win32

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

>>> from emp.models import EmpMaster

>>> type(EmpMaster.objects)

<class 'django.db.models.manager.Manager'>

>>> rec=EmpMaster.objects.get(eid=101)

>>> rec

<EmpMaster: 101,satya narayana,41200.99,M,1002>


72

>>> rec.eid

101

>>> rec.ename

'satya narayana'

>>> rec.salary

41200.99

>>> rec.salary=rec.salary+800

>>> rec.save()

>>> rec

<EmpMaster: 101,satya narayana,42000.99,M,1002>

>>> emprecs=EmpMaster.objects.all()

>>> emprecs

<QuerySet [<EmpMaster: 101,satya narayana,42000.99,M,1002>, <EmpMaster: 102,manas,25000.

55,M,1002>, <EmpMaster: 103,krishna,30000.55,M,1003>]>

>>> emprecs[0]

<EmpMaster: 101,satya narayana,42000.99,M,1002>

>>> emprecs[1]

<EmpMaster: 102,manas,25000.55,M,1002>

>>> emprecs[0:2]

<QuerySet [<EmpMaster: 101,satya narayana,42000.99,M,1002>, <EmpMaster: 102,manas,25000.

55,M,1002>]>

>>> emprecs[1:3]

<QuerySet [<EmpMaster: 102,manas,25000.55,M,1002>, <EmpMaster: 103,krishna,30000.55,M,10

03>]>

>>> for rec in emprecs:

... print(rec)

...

101,satya narayana,42000.99,M,1002

102,manas,25000.55,M,1002
73

103,krishna,30000.55,M,1003

>>> emprecs.filter(deptno=1002)

<QuerySet [<EmpMaster: 101,satya narayana,42000.99,M,1002>, <EmpMaster: 102,manas,25000.

55,M,1002>]>

>>> emprecs.filter(deptno=1002,gender='M')

<QuerySet [<EmpMaster: 101,satya narayana,42000.99,M,1002>, <EmpMaster: 102,manas,25000.

55,M,1002>]>

>>> emprecs.order_by('ename')

<QuerySet [<EmpMaster: 103,krishna,30000.55,M,1003>, <EmpMaster: 102,manas,25000.55,M,10

02>, <EmpMaster: 101,satya narayana,42000.99,M,1002>]>

>>> emprecs.order_by('-ename')

<QuerySet [<EmpMaster: 101,satya narayana,42000.99,M,1002>, <EmpMaster: 102,manas,25000.

55,M,1002>, <EmpMaster: 103,krishna,30000.55,M,1003>]>

Django Forms:

• we can define html forms through the django form class instead of writing the
code explicitly.

• Any user defined class which is extended by django.forms.

ex:

from django import forms

class classname (forms.Form)

Each attribute of form class represents one html control of the HTML form.

we can specify the type of attribute in the form class by using pre-define class called

django.forms module.

We can create the from class objects within the views and we can forward that object to the

templates ( html files )


74

We can use the form class object within the html files by using django-template-scripting-
language.

Form class objects are reusable objects so that we will get the templates reusability.

• The data which is submitted by the end user through the form, we can store them
into the form class object. we can apply the validations to form controls by the
methods of form class.

• we can read the data from controls, store them into the model class objects.

• All the form classes are related to application, we should define within the
form.py files.

• Forms that map to a particular model are called ModelForms.

Forms Attributes:

For each field we describe, the default widgets (ex: bottom, checkbox, ...) are used, if you don't
specify widget.

1. BooleanField:

Default widget: checkbox Input

Empty value: False

Normalizes to: Python true or false value

Validates that the value is true

2. CharField:

Defaultwidget: Text Input

Empty value: False

Normalizes to: a string

validates max-length or min-length if they are provided otherwise, all i/p's are valid

3. Choicefield:

Default widget: Select

Empty value: "(an empty string)"

Normalizes to: a string


75

validations that the given value exists in the list of choices.

4. DateField:

Default widget: DataInput

Empty value: None

Normalizes to: A python datetime. data object

Validations that the given value is either a datetime.data, datetime.datetime or string formatted in
a particular date format.

Eg: input_formats:

A list of formats used to attempt to convert a string to a valid date time object.

If no input format argument is provided, the default input format are:

' % Y - % m -% d' # '2018-08-28'

'% m/ % d/% Y' # '08/28/2018'

' % m /% d/ %y' # '08/28/18'

5. DateTimeField:

Default widget: Date Time Input

Empty Value: None

Normalizes to: A python datetime. datetime object.

Validations that the given string is either a datetime. datetime or datetime or string formatted in a
particular date format.

INPUT FORMS:

A list of formats used to attempt to convert a string to a valid datetime.datetime object.

If no input_format argument is provided, the default input formats are:

'%Y-%m-%d %H-%M-%S' #'2018-08-28 14:30:5'

'%m-%d-%Y %H:%M:%S' #'08/28/2018 14:30:5'

'%m-%d-%y %H:%M:%S' #'08/28/18 14:30:5'

DecimalFiled:
76

Default widget: Number Input

empty value:None

validates that the given value is a decimal

leading and tailing white spaces are not read.

FileField:

Default widget: clearable FileInput

empty value:None

Normalizes to: An uploaded File object that wraps the file content and filename into a single
object.

validate that non-empty file data has been bound to the form

EmailField:

Default widget: Email input

empty value:' '

Normalizes to: A string

IntegerField:

Default widget: Number Input

empty value:None

Normalizes to: A python integer

validates that given value is a integer. leading and tailing whitespaces is allowed as in python's
int() fun

ImageField:

Default widget: clearable file input

empty value:None

Normalizes to: an uploaded file object that wraps the file content and filename into a single
object.
77

MulitipleChoiceField

Default widget: select multiple

empty value:[](empty list)

Normalizes to: to a list of things

validates that the ecery value in the given list of values exists in the list of choices

RegexField:

Default widget: text input

empty value: ' '

Normalizes to: A string

validates that the given value matches against a certain regular expressions

TimeField

Default widget: TextInput

empty value:None

Normalizes to: A python datetime.time object

validates that the given value is either a datetime.time object or string formated in particular tine
format

input-formats

a list of formats used to attempt to convert a string to a valied datetime.time object

of no input-format argument is provided, the default i.p formats are:

'%H:%M:%S' #'11:15:49'

'%H:%M' #'11:15'

URLFiled:

default widget :URLInput

Empty value:''

Normalizes to: a string


78

validates that the given value is a valid URL or not

RelationShips:

two fileds are available for representing relationship b/w models and forms . they are

1)ModelChoiceField

2)ModelMultipleChoiceFiled

these fileds will place either are model object(in the case of ModelChoiceField)or multiple
model objects(in case if ModelMultipleChoiceField)

ModelChoiceFiled:

default widget: selectr

empty value:None

Normalizes to : A model instance

validates that the given exists in the queryset

ModelMultipleChoice :

default widget: select multiple

empty value : an empty QuerySet(self.Query.none())

Normalizes to : a QuerySet of model instances. validates that the every id in the given list of
values exits in the QuerySet

6. DecimalField:

Default widget: Number Input when field

Empty value: None

Normalizes to: A python decimal

Validations that the given value is a decimal.

Leading any trailing white space ignored.


79

FormFiled Attributes:

1. required: if required=true, the field should not be left blank. Fields are required by default, so
you would set required to false to allow blank values in the form.

2. Label: used when rendering the field into Html. If a label is not specified, Django will create
one form the field name by capitalizing the 1st letter and replacing underscores with spaces (eg:
renewal date)

3. label suffix: By default a colon is displayed after the label (eg: renewal date:)

This argument allows you to specify a different suffix containing other characters

4. initial: the initial value for the field when the form is displayed.

5. widget: The display widget to use

6. help_text: Additional text that can be displayed in forms to explain how to use the field.

7. Error_messages:

A list of error messages for each field. you can override them with your own message if needed.

8. Validations:

A list of functions that will be called on the field when it is validated.

9. Localize:

Enables the localization of form data input.

10.Disabled:

this field is displayed but its value can't be edited if this is true. The default value is false.

WHY WE USE META CLASS INSIDE THE MODEL FORM IN DJANGO?

Meta class is simply an inner class in django, the use of meta class is simply to provide meta data
to the model from class.

WHAT IS META DATA?

Any information that is not a form field can be considered as meta data.

Mandotary meta options are


80

1. model: model class to user for creating forms

2. fields: list of fields included in the form control

3. exclude: list of excluded fields of form control

Eg: forms.py:

class EmployeeForm(forms.ModelForm):

class Meta:

model= Employee

fields= "__all__"

exclude=["id","date_of_join",…..]

form validatations :

django provides built-in methods to validate form data automatically

django form is submitted only, if it has csrf_token.

it uses a clean and easy approach to validate data.

is_valid():

-----------

this method is used to perform validations for each field of the form, it is defined in django form
class. it returns True if data is valid

working with form templates:

all you need to do to get your form into a template is to place form instance into the template
context, {{form}} will render its <label> and <input>elements appropriately.

{{form.as_table}} will render them as table cells wrapped in <tr>tags

{{form.as_p}} will render them wrapped in <p>tag

{{form.as_ul}} will render them wrapped in <li>tags.


81

The Django Administration Site

The Django admin application can use your models to automatically build a site area that you
can use to create, view, update, and delete records. This can save you a lot of time during
development, making it very easy to test your models and get a feel for whether you have the
right data. The admin application can also be useful for managing data in production, depending
on the type of website. The Django project recommends it only for internal data management
(i.e. just for use by admins, or people internal to your organization), as the model-centric
approach is not necessarily the best possible interface for all users, and exposes a lot of
unnecessary detail about the models.
All the configuration required to include the admin application in your website was done
automatically when you created the skeleton project. Just you need to add your models to the
admin application to register them.

To create super user


$python manage.py createsuperuser

note: here you may get error like database name auth_user does not exists
to overcome the above problems run following two commands at terminal
$python manage.py migrate auth
$python manage.py migrate

To add admin declarations for HotelSuprabat, UserDetails, Tenants tables

steps:
-------
82

remove comments from all options of your INSTALLED_APPS like


'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'

Also uncomment all the lines in the MIDDLEWARE_CLASSES setting tuple like
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XframeOptionsMiddleware',
add following To admin.py from the HotrlManagement app (i.e /mysite/books/admin.py)
from django.contrib import admin
from loginapp.models import UserDetails
from Hotel.models import HotelSuprabat, tenants
admin.site.register(UserDetails)
admin.site.register(HotelSuprabat)
admin.site.register(tenants)

USING THE ADMIN INTERFACE


Now you can visit the URL given to you by Django (http://127.0.0.1:8000/admin/ in the
preceding example),log in, and play around.
83

You’ll use the username and password you set up when you added your superuser. Once you’re
logged in, you’ll see that you can manage users, groups, and permissions.
Each object given an Admin declaration shows up on the main index page as follows.

Links to add and change objects lead to two pages we refer to as object change lists and edit
forms.
click on any table to show table(for ex: HotelSuprabat) contents
84

to add records to the suprabat table click on ‘ADD HOTEL SUBRABAT’ button.
fill details as follows

to save record click on ‘save’ button.

note: when you click on save button, if any filed is missing, you will validation error follows
85

to modify existing record, click on any record, you will get following page.
we can modify any filed, click on ‘save’ button.

to delete required record, select action combo box, select required record, then click on ‘go’
button. then we will get following page.
86

to delete record click on ‘yes, I’m sure’ button

When you edit an existing object, you’ll notice a History button in the upper-right corner of the
window. Every change made through the admin interface is logged, and you can examine this
log by clicking the History button.
87

to show only required fileds from the table(for ex UsersDetails)


then go to admin.py( i.e /mysite/books/admin.py)write the following code
from loginapp.models import UserDetails
from Hotel.models import HotelSuprabat, tenants

class UsersAdmin(admin.ModelAdmin):
list_display = ('firstname', 'phone', 'gender')
list_filter = ['gender']
ordering = ('firstname',)
search_fields = ('firstname',)
admin.site.register(UserDetails, UsersAdmin)
Each of those lines instructed the admin interface to construct a different piece of this interface:
• The list_display option controls which columns appear in the change list table. By default, the
change list
displays only a single column that contains the object’s string representation. Here, we’ve
changed that to show the firstname, phone, gender
• The list_filter option creates the filtering bar on the right side of the list. We’ve allowed
filtering by gender.
You can instruct the admin interface to filter by any field, but foreign keys, dates, Booleans, and
fields with a choices attribute work best. The filters show up as long as there are at least 2 values
to choose from.
• The ordering option controls the order in which the objects are presented in the admin interface.
It’s simply alist of fields by which to order the results; prefixing a field with a minus sign
reverses the given order. In this example, we’re ordering by firstname
• Finally, the search_fields option creates a field that allows text searches. It allows searches by
the ‘firstname’ field.

Django Sessions
HTTP is a stateless protocol. In other words, when a request is sent to the
server, it has no idea whether you are requesting the page for the first time
or you are the same person who has visited this page thousand times before.
This lack of statelessness was a big problem among developers of an e-
commerce website because persistence among request could be used to
88

recommend products or display products in a shopping cart. To mitigate this


problem there are two ways

1) Sessions

2) Cookie

Sessions are the mechanism used by Django (and most of the Internet) for keeping track
of the "state" between the site and a particular browser. Sessions allow you to store
arbitrary data per browser, and have this data available to the site whenever the browser
connects. Individual data items associated with the session are then referenced by a
"key", which is used both to store and retrieve the data.

Django uses a cookie containing a special session id to identify each browser and its
associated session with the site. The actual session data is stored in the site database
by default (this is more secure than storing the data in a cookie, where they are more
vulnerable to malicious users). You can configure Django to store the session data in
other places (cache, files, "secure" cookies), but the default location is a good and
relatively secure option.

Enabling sessions

Sessions are implemented via a piece of middleware called

'django.contrib.sessions.middleware.SessionMiddleware'.

If you don’t want to use sessions, you might as well remove the SessionMiddleware line

from MIDDLEWARE and 'django.contrib.sessions' from your INSTALLED_APPS.

It’ll save you a small bit of overhead.

By default, Django stores sessions in your database

(using the model django.contrib.sessions.models.Session).


89

If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your

INSTALLED_APPS setting.

Once you have configured your installation, run manage.py migrate to install the single database

table(django_session) that stores session data.

SESSION_COOKIE_AGE

Default: 1209600 (2 weeks, in seconds)

The age of session cookies, in seconds.

SESSION_COOKIE_NAME

Default: 'sessionid'

The name of the cookie to use for sessions. This can be whatever you want.

SESSION_COOKIE_PATH

Default: '/'

The path set on the session cookie. This should either match the URL path of your Django

installation or be parent of that path.

This is useful if you have multiple Django instances running under the same hostname. They can

use different cookie paths, and each instance will only see its own session cookie.

SESSION_COOKIE_SECURE
90

Default: False

If this is set to True, the cookie will be marked as “secure,” which means browsers may ensure
that

the cookie is only sent under an HTTPS connection.

SESSION_EXPIRE_AT_BROWSER_CLOSE

Default: False

if the value is False session will not be deleted sience default inactive session time period is 2
weeks.

To browser length cookies go to settings.py set above property to True as follows

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',

...............................

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

SESSION_SAVE_EVERY_REQUEST

Default: False

To set above property true to save the session data on every request go to settings.py as follows

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',

...............................
91

SESSION_SAVE_EVERY_REQUEST=True

to store and read value from the session:

request.session["username"]="satya"

request.session["password"]="satya123"

user=request.session["username"]

fav_color = request.session['fav_color']

to delete session

del request.session['fav_color'].

This raises KeyError if the given key isn’t present in the session.

To check specified key is present or not

'fav_color' in request.session (or) request.session.has_key("fav_color")

to read value of the particular key and to get default value if the key is not present

get(key, default=None)

fav_color = request.session.get('fav_color', 'red')

methods of session

keys()

items()

clear()

It also has these methods:

flush()

Deletes the current session data from the session and deletes the session cookie. This is used
92

if you want to ensure that the previous session data can’t be accessed again from the user’s
browser.

set_expiry(value)

Sets the expiration time for the session. You can pass a number of different values:

If value is an integer, the session will expire after that many seconds of inactivity.

For example, calling request.session.set_expiry(300) would make the session expire in 5


minutes.

If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.

Note: Reading a session is not considered activity for expiration purposes. Session expiration is

computed from the last time the session was modified.

get_expiry_age()

Returns session life time in seconds

get_expiry_date()

Returns the date this session will expire.

clear_expired()

Removes expired sessions from the session store.

def login(request):

username = 'not logged in'


93

if request.method == 'POST':

MyLoginForm = LoginForm(request.POST)

if MyLoginForm.is_valid():

username = MyLoginForm.cleaned_data['username']

request.session['username'] = username

else:

MyLoginForm = LoginForm()

return render(request, 'loggedin.html', {"username" : username}

def formView(request):

if request.session.has_key('username'):

username = request.session['username']

return render(request, 'loggedin.html', {"username" : username})

else:

return render(request, 'login.html', {})

from django.conf.urls import patterns, url

from django.views.generic import TemplateView

urlpatterns = patterns('myapp.views',

url(r'^connection/','formView', name = 'loginform'),

url(r'^login/', 'login', name = 'login'))


94

def logout(request):

try:

del request.session['username']

except:

pass

return HttpResponse("<strong>You are logged out.</strong>")

Cookies Handling:
Sometimes you might want to store some data on a per-site-visitor basis as per the requirements
of your web application.

What is Cookie?
A cookie is a small piece of data stored in the user's browser which is sent by the server. They
are commonly used to store user preferences.
This is how cookies work in general:
• The browser sends the request to the server.
• The server sends the response along with one or more cookie to the browser.
• The browser saves the cookie it received from the server. From now on, the browser will
send this cookie to the server, every time a request is made to the server. The browser
will keep sending the cookie to the server along with each request until the cookie
expires.
• When the cookie expires, it is removed from the browser.
Cookie was first implemented by a programmer named Louis Montulli in 1994 at Netscape
Communications in their Netscape Browser.

Creating Cookies
We can create cookies using the set_cookie() method of the request object. The syntax of the
method is:
Syntax: set_cookie(name, value, max_age=None)
• name: name of the cookie
95

• value: value you want to store in the cookie


• max_age: age of the cookie in seconds. After that, it will expire. It is an optional
argument, if not given then the cookie will exist until the browser is closed.

Reading cookies
Every request object in Django has a COOKIE attribute which acts like a dictionary. We can use
COOKIE to access a cookie value like this:
request.COOKIE['cookie_name']

When you read cookie data, it will be returned as strings. That means, even if you store an
integer 100 in a cookie, it will be returned as '100'.

A view to count the visits


Open blog's views.py file and add the following view to the end of the file.
views.py
def track_user(request):
if not request.COOKIES.get('visits'):
response = HttpResponse("This is your first visit to the site. "
"From now on I will track your vistis to this site.")
response.set_cookie('visits', '1', 3600 * 24 * 365)
else:
visits = int(request.COOKIES.get('visits')) + 1
response = HttpResponse("This is your {0} visit".format(visits))
response.set_cookie('visits', str(visits), 3600 * 24 * 365)
return response

After that, add the following URL pattern to the beginning urlpatterns list in blog's urls.py file.
urls.py

Here are few important points about above view:


• we are updating the value of the cookie and sending it to the browser every time the user
visits the site, which is necessary otherwise we wouldn't be able to count visits made by
the user.
• Every time the user visits http://127.0.0.1:8000/track_user/, we are updating cookie
expiry date as well, which starts from that request.
96

You might also like