Professional Documents
Culture Documents
Django Sessions
Django Sessions
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
• 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:
<html>
<head>
</head>
<body>
<h1 style = "color:blue;font-size:50px;font-family:Arial;text-align:center;"> Welcome
<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
}
</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 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,
• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
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>
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
</html>
</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
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>
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
<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
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
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>
</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 <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!
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
• 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.
Advantages of Django:
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.
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 Python
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.
c:\>django-admin.py --version
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.
or
c:\...> pip install mysql-connector-python
or
c:\......>pip install mysqlclient
Architecture of Django
41
• 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.
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.
Ex : DateProject
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.
The “DateProject” subfolder: This folder is the actual python package of your project. It
contains four files:
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.
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
Although the development server is extremely nice for, well, development. The development
server can handle only a single request at a time reliably.
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:
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.
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.
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.
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.
open urls.py file present in DateApp subfolder present in project folder which is created
views.py:
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.
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.
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),
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:
Then http://127.0.0.1:8000/time/plus/24/.
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)]
'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:
{% comment %}
---------------
---------------
{% endcomment %}
For loop
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
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>
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
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
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
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
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
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.
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
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):
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
71
'emp'
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
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on
win32
(InteractiveConsole)
>>> type(EmpMaster.objects)
<class 'django.db.models.manager.Manager'>
>>> rec=EmpMaster.objects.get(eid=101)
>>> rec
>>> rec.eid
101
>>> rec.ename
'satya narayana'
>>> rec.salary
41200.99
>>> rec.salary=rec.salary+800
>>> rec.save()
>>> rec
>>> emprecs=EmpMaster.objects.all()
>>> emprecs
>>> emprecs[0]
>>> emprecs[1]
<EmpMaster: 102,manas,25000.55,M,1002>
>>> emprecs[0:2]
55,M,1002>]>
>>> emprecs[1:3]
03>]>
... 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)
55,M,1002>]>
>>> emprecs.filter(deptno=1002,gender='M')
55,M,1002>]>
>>> emprecs.order_by('ename')
>>> emprecs.order_by('-ename')
Django Forms:
• we can define html forms through the django form class instead of writing the
code explicitly.
ex:
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
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 Attributes:
For each field we describe, the default widgets (ex: bottom, checkbox, ...) are used, if you don't
specify widget.
1. BooleanField:
2. CharField:
validates max-length or min-length if they are provided otherwise, all i/p's are valid
3. Choicefield:
4. DateField:
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.
5. DateTimeField:
Validations that the given string is either a datetime. datetime or datetime or string formatted in a
particular date format.
INPUT FORMS:
DecimalFiled:
76
empty value:None
FileField:
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:
IntegerField:
empty value:None
validates that given value is a integer. leading and tailing whitespaces is allowed as in python's
int() fun
ImageField:
empty value:None
Normalizes to: an uploaded file object that wraps the file content and filename into a single
object.
77
MulitipleChoiceField
validates that the ecery value in the given list of values exists in the list of choices
RegexField:
validates that the given value matches against a certain regular expressions
TimeField
empty value:None
validates that the given value is either a datetime.time object or string formated in particular tine
format
input-formats
'%H:%M:%S' #'11:15:49'
'%H:%M' #'11:15'
URLFiled:
Empty value:''
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:
empty value:None
ModelMultipleChoice :
Normalizes to : a QuerySet of model instances. validates that the every id in the given list of
values exits in the QuerySet
6. DecimalField:
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.
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:
9. Localize:
10.Disabled:
this field is displayed but its value can't be edited if this is true. The default value is false.
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.
Any information that is not a form field can be considered as meta data.
Eg: forms.py:
class EmployeeForm(forms.ModelForm):
class Meta:
model= Employee
fields= "__all__"
exclude=["id","date_of_join",…..]
form validatations :
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
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.
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.
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
steps:
-------
82
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)
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
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
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
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
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
'django.contrib.sessions.middleware.SessionMiddleware'.
If you don’t want to use sessions, you might as well remove the SessionMiddleware line
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
SESSION_COOKIE_AGE
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
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
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.
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
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 read value of the particular key and to get default value if the key is not present
get(key, default=None)
methods of session
keys()
items()
clear()
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.
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
get_expiry_age()
get_expiry_date()
clear_expired()
def login(request):
if request.method == 'POST':
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
request.session['username'] = username
else:
MyLoginForm = LoginForm()
def formView(request):
if request.session.has_key('username'):
username = request.session['username']
else:
urlpatterns = patterns('myapp.views',
def logout(request):
try:
del request.session['username']
except:
pass
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
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'.
After that, add the following URL pattern to the beginning urlpatterns list in blog's urls.py file.
urls.py