0% found this document useful (0 votes)
26 views387 pages

Python Advance

The document provides a comprehensive overview of Python lists and tuples, detailing their characteristics, methods for manipulation, and examples of usage. It covers topics such as indexing, updating, deleting elements, and the differences between mutable lists and immutable tuples. Additionally, it includes sample programs demonstrating various list operations and tuple creation.

Uploaded by

yashikamuthaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views387 pages

Python Advance

The document provides a comprehensive overview of Python lists and tuples, detailing their characteristics, methods for manipulation, and examples of usage. It covers topics such as indexing, updating, deleting elements, and the differences between mutable lists and immutable tuples. Additionally, it includes sample programs demonstrating various list operations and tuple creation.

Uploaded by

yashikamuthaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 387

How to reduce data usage ?

 Search gpedit.msc click computer configuration administrative


templateswindows components  windows update double click
configure automatic update  click disable apply  ok
Python Lists
 A List in Python is used to store the sequence of various types of data.
 Python Lists are mutable type its mean we can modify its element after it created.
 However, Python consist of six data-types that are capable to store the sequence,
but the most common and reliable type is the list.
 A list can be defined as a collection of values of items of different types.
 The items in the list are separated with the comma(,) and enclosed with the square
brackets[].

Prg29: To Write a Python program for (List Data Type):

l1=[100,200,300,50]
l2=["Apple","Orange","Cake","Chocolate"]
print("Number List:")
for i in l1:
print(i,end=' ' )
print("\n")
print("String List:")
for i in l2:
print(i,end=' ')

OUTPUT:
Number List:
100 200 300 50
String List:
Apple Orange Cake Chocolate

Lists Indexing and Splitting:

 The indexing processed in the same way as it happens with the string.
 The elements of the list can be accessed by using the slice operator[].
 The index starts from 0 and goes to length -1 .
 The first element of the list is stored at the 0th index, the second element
of the list is stored at the 1st index, and so on.
Example:
List=[10,23,45,66,98,12]
List[0]=10
List[1]=23
List[2]=45
List[3]=66
List[4]=98
List[5]=12

Prg30: To Write a Python program for (List Data Type):

li=[11,22,3,4,5,62,72]
print("The first element is:",li[0])
print("The 5th element is:",li[4])
# Slicing element
print(li[3:6]) # From index of 3rd element to 6th element
print(li[0:7:2]) # From 0th element to leave one element to display next one
OUTPUT:
The first element is: 11
The 5th element is: 5
[4, 5, 62]
[11, 3, 5, 72]

 Unlike other languages, Python provides the flexibility to use the negative indexing
also.
 The negative indices are counted from the right.
 The last element (Rightmost) of the list has the index -1 ; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
List=[10,23,45,66,98,12]

Forward Direction 
0th 1st 2nd 3rd 4th 5th
10 23 45 66 98 12
-6th -5th -4th -3rd -2nd -1st
Backward Direction 

Prg31: To Write a Python program for (Backward List ):

li=[11,22,3,7,5,62,72]
print("The first of Backward element is:",li[-1])
print("The 4th Backward element is:",li[-4])

OUTPUT:
The first of Backward element is: 72
The 4th Backward element is: 7

Updating List Values:

 Lists are the most versatile data structures in Python since they are mutable, and
their values can be updated by using the slice and assignment operator.
 Python also provides append() and insert() methods, which can be used to add
values to the list.

Prg32: To Write a Python program for (Update existing List Values):


li=[33,44,55,66,77,88]
print(" Before Update the element values :")
print(li)
li[2]=10 # It will assign value to the 2nd index
print(" After Update the element values :")
print(li)
li[1:4]=[89,79,898] # To adding values for multiple element
print(" After Update multiple element values :")
print(li)
OUTPUT:
Before Update the element values :
[33, 44, 55, 66, 77, 88]
After Update the element values :
[33, 44, 10, 66, 77, 88]
After Update multiple element values :
[33, 89, 79, 898, 77, 88]

Deleting List Values:


 The List elements can also be deleted by using the del keyword and also provides us
the remove() method.

Prg33: To Write a Python program for (Deleting List Values):


li=[33,44,55,66,77,88]
print(" Before Delete the element values :")
print(li)
del li[2]# It will delete the element 2nd index (i.e = 55)
print(" After deleted the element values :")
print(li)

OUTPUT:
Before Delete the element values :
[33, 44, 55, 66, 77, 88]
After deleted the element values :
[33, 44, 66, 77, 88]
Adding Element to the List:
 Python provides append() function which is used to add an element to the list.
 However, the append() function can only add value to the end of the list.

Prg34: To Write a Python program for (Taking value of the element from the
User to the List):
m1=[] # Declaring the empty list
n=int(input(" Enter the Number of elements in the List:"))
for i in range(0,n): # For loop to take the input upto n-numbers
m1.append(input("Enter the Item:"))
print("Printing the list Items:")
for i in m1: # traversal loop to print the list items
print(i,end=' ')

OUTPUT:
Enter the Number of elements in the List:3
Enter the Item:22
Enter the Item:33
Enter the Item:44
Printing the list Items:
22 33 44
Prg35: To Write a Python program for (Taking value of the element from the
User to the List and find Odd and Even number and Maximum and Minimum
Number in the list ):

m1=[] # Declaring the empty list


even=0
odd=0
n=int(input(" Enter the Number of elements in the List:"))
for i in range(0,n): # For loop to take the input upto n-numbers
m1.append(int(input("Enter the Item:")))
for i in m1:
if i%2==0:
even=even+1
else:
odd=odd+1
print("Total even Numbers:",even)
print("Total odd Numbers:",odd)
print("Maximum Number in the given list:",max(m1))
print("Minimum Number in the given list:",min(m1))
OUTPUT:
Enter the Number of elements in the List:5
Enter the Item:4
Enter the Item:5
Enter the Item:8
Enter the Item:12
Enter the Item:32
Total even Numbers: 4
Total odd Numbers: 1
Maximum Number in the given list: 32
Minimum Number in the given list: 4
Prg35: To Write a Python program to remove the duplicate element of the
list ):
m1=[2,2,5,6,7,7,12,3,21,5]
m2=[]
print(" Before removing Duplicate values")
print(m1)
for i in m1:
if i not in m2: # Here i value is not in m2 list then the items will store in list of m2
m2.append(i)
sum=sum+i # Find Total sum of List m2 list
print(" After removing Duplicate values")
print(m2)
print("sum is:",sum)
OUTPUT:
Before removing Duplicate values
[2, 2, 5, 6, 7, 7, 12, 3, 21, 5]
After removing Duplicate values
[2, 5, 6, 7, 12, 3, 21]
Sum is: 56
Prg36: To Write a Python program to find the lists consist of at least one
common element of the list ):
m1=[56,43,12,43,45,67]
m2=[23,3,1,43,5,6]
for x in m1:
for y in m2:
if x==y:
c=x # Here the common value store in C
print("Common element is:",c)
OUTPUT:
Common element is: 43
Prg37: To Write a Python program Fact of List:
m1=[1,2,3,4,5]
m2=[5,6,7,8,9]
print("m1 list is:",m1)
print("m2 list is:",m2)
print(" Addition two list of m1 and m2")
c=m1+m2 # here adding two list
print(c)
m3=[2,3]
print("m3 list is:",m3)
d=m3*3 # Here m3 list multiple of 3 times
print(" 3 time multiple of list m3 is:")
print(d)
m4=[[1,2],[2,3],[3,4]] # here its called nested list
print(" Nested list of M4 is")
print(m4)
# Need print 2nd list of m4
print("2nd list of M4 is:")
print(m4[1])
# need to print 2nd list and 2 element of m4
print("2nd column of 2nd list of m4 is:")
print(m4[1][1]) # it means 1st row 2nd column
print("1st column of 2nd list of m4 is:")
print(m4[1][0]) # it means 1st row 1 st column like as matrix

OUTPUT:
m1 list is: [1, 2, 3, 4, 5]
m2 list is: [5, 6, 7, 8, 9]
Addition two list of m1 and m2
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
m3 list is: [2, 3]
3 time multiple of list m3 is:
[2, 3, 2, 3, 2, 3]
Nested list of M4 is
[[1, 2], [2, 3], [3, 4]]
2nd list of M4 is:
[2, 3]
2nd column of 2nd list of m4 is:
3
1st column of 2nd list of m4 is:
2
Prg38: To Write a Python program Functions Of List Data Type:

m1=[2,4,6,5,18]
print("length of list m1 is:",len(m1))
print("length of list m1 is:",min(m1))
print("length of list m1 is:",max(m1))
s="Krish"
print("String is:",s)
s1=list(s) # here s is convert as list that store into s1
print(" List values of s1 is:",s1)
m2=[] # here it is empty list
# if you need to add 0 numbers in list
print("Additing 20numbers into the list of m2 is:")
for i in range(20):
m2.append(i) # here 20 number will be added
print(m2)
print("Additing New element at the end of list of m2 is:")
m2.append(18) # this new element added at the end of list
print(m2)
print("find 18 presented in the list of m2 is:")
m2.count(18) # this function used to find the same number from the list
print("Extend list m1 to s1 is:")
m1.extend(s1)
print(m1)
m3=[5,6,7,9,10]
print("Before insert value in m3 list is:")
print(m3)
print("After insert value in m3 list is:")
m3.insert(3,8)
print(m3)
# pop it's a one concept of LIFO( Last in First out) in Data structure
m3.pop()
print("Last in first out(Pop):")
print(m3)
#if you remove any element of given list using pop() function
m3.pop(4)
print("after remove 4th element of list m3 is:")# that is 9
print(m3)
# if you want to value based in the list we can use remove() function
m3.remove(6)
print(" After remove the value of 6 from the list m3 is:")
print(m3)
# if you want to reverse a list you can use reverse() function
m3.reverse()
print("After reverse list of m3 is:")
print(m3)
# if you want to sort of your list you can use sort() function
m4=[12,5,10,3,20]
print("Before Sort of list M4 is:",m4)
m4.sort()
print("after Sort of list M4 is:",m4)

OUTPUT:
length of list m1 is: 5
length of list m1 is: 2
length of list m1 is: 18
String is: Krish
List values of s1 is: ['K', 'r', 'i', 's', 'h']
Adding 20numbers into the list of m2 is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Adding New element at the end of list of m2 is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 18]
find 18 presented in the list of m2 is:
Extend list m1 to s1 is:
[2, 4, 6, 5, 18, 'K', 'r', 'i', 's', 'h']
Before insert value in m3 list is:
[5, 6, 7, 9, 10]
After insert value in m3 list is:
[5, 6, 7, 8, 9, 10]
Last in first out(Pop):
[5, 6, 7, 8, 9]
after remove 4th element of list m3 is:
[5, 6, 7, 8]
After remove the value of 6 from the list m3 is:
[5, 7, 8]
After reverse list of m3 is:
[8, 7, 5]
Before Sort of list M4 is: [12, 5, 10, 3, 20]
after Sort of list M4 is: [3, 5, 10, 12, 20]

Python Tuple
 Python Tuple is used to store the sequence of immutable Python Objects.
 The tuple is similar to lists since the value of the items stored in the list can be
changed , whereas the tuple is immutable, and the value of the items stored in the
tuple cannot be changed.

Creating Tuple:
 A tuple can be written as the collection of comma-separated(,) values enclosed with
the small() brackets.
 The parentheses are optional but it is good practice to use.
Prg39: To Write a Python program For Tuple Data Type:
t1=(101,"Madhi",31)
t2=("Biriyani","Apple","Orange")
t3=10,22,32,45
print(t1)
print(t2)
print(t3)
OUTPUT:
(101, 'Madhi', 31)
('Biriyani', 'Apple', 'Orange')
(10, 22, 32, 45)
Note: The Tuple which is created without using parentheses is also known as tuple
packing.

Prg40: To Write a Python program Functions of Tuple Data Type:


a=[1,2,3] # it is called as List
b=(1,2,3) #it is called as Tuple
print("the type a is:",type(a))
print("the type a is:",type(b))
print("before change value list:")
print(a)
a[1]=0 # here we can change value because it is list and also mutable obejct
print("before change value list:")
print(a)

#b[1]=0 # here we can't change value because tuple is immutable obejct


# here leads error
# to Add new element in tuple
b=b+(10,) # adding new element in the tuple
print(" after adding new value in tuple is:",b)

print(" the index of 2 in Tupe is :",b[2]) # here we can read the values from tuple but can't
modify
print(" the index starts with 2 is:",b[2:])
print(" the index before of 2 is:",b[:2])

del b # we can't delete element from tuple but we can delete entire tuple here

#print(b) Here leads error (i.e : name 'b' is not defined)


c=(7,5,6,9,78) # we can iterate tuple
print("iteration of C - tuple is")
for i in c:
print(i,end=' ')
print("the length of tuple C is:",len(c))
print(" the minimum value of tuple C is:",min(c))
print(" the maximum value of tuple C is:",max(c))
print(" the value 78 presented in tuple C is:",c.count(78))
print(" the index value of 78 in tuple C is:",c.index(78))

OUTPUT:
the type a is: <class 'list'>
the type a is: <class 'tuple'>
before change value list:
[1, 2, 3]
before change value list:
[1, 0, 3]
after adding new value in tuple is: (1, 2, 3, 10)
the index of 2 in Tupe is : 3
the index starts with 2 is: (3, 10)
the index before of 2 is: (1, 2)
iteration of C - tuple is7 5 6 9 78
the length of tuple C is: 5
the minimum value of tuple C is: 5
the maximum value of tuple C is: 78
the value 78 presented in tuple C is: 1
the index value of 78 in tuple C is: 4

Python Set
 A Python set is the collection of the unordered items. Each element in the set must
be unique( no duplicate), immutable, and the sets remove the duplicate elements.
 Seta are mutable which means we can modify it after its creation.
 Unlike other collection in Python, there is no index attached to the elements of the
set, i.e, we can’t directly access any element of the set by the index.
 However we can get the list of elements by looping through the set.

Creating a Set:
 The set can be created by enclosing the comma(,) separated immutable items with
the curly braces {}.
 Python also provides the set() method, which can be used to create the set by the
passed sequence.
 Python provides the add() method is used to add a single element in the set.
 And also provides the update() method is used to add multiple elements to the set.

Prg41: To Write a Python program Functions of Set Data Type:


a=[1,2,1,2,1,2] # it's list can access duplicate
b={1,2,3}
print("Type A Is:",type(a))
print("Type B Is:",type(b))
c={} # we imagine it's a set but it's taking as dictionary we will study about later
print("Type C Is:",type(c))
# If you need empty set means
d=set() # Now it's a empty set
print("Type D Is:",type(d))
# If you add single element in the set by using add() method
d.add(5) # here 5 will be add in the set of 'd'
print(" D set values:",d)
# to add multiple elements in the set
d.update('6','7','8') # update() method only add strings
print(" D set values:",d)
n={1,2,3,4,5}
print("Before remove value in set",n)
n.remove(5)
print("After remove value in set",n)
n.pop() # it will remove 1st element of set
print("After remove First value in set",n)
n.clear() # it will remove all element in the set
print("After remove All value in set",n)
ts={(1,2),(3,4)} # it is inside of tuple with set
print(" Tuple inside of set:",ts)

OUTPUT:
Type A Is: <class 'list'>
Type B Is: <class 'set'>
Type C Is: <class 'dict'>
Type D Is: <class 'set'>
D set values: {5}
D set values: {'6', 5, '7', '8'}
Before remove value in set {1, 2, 3, 4, 5}
After remove value in set {1, 2, 3, 4}
After remove First value in set {2, 3, 4}
After remove All value in set set()
Tuple inside of set: {(1, 2), (3, 4)}
Prg42: To Write a Python program Copy Function of Set Data Type:
a={1,2,4}
# if you want to copy element from set 'a'
b=a # here the data copied to set 'b' and sharing same memory
print("Original value of set 'a':",a)
print("Copied value of set 'b':",b)
# Here we have one doubt , if we add anything valut to set 'a'
# The value will also affect of set 'b' ? ... Ans: Yes
a.add(5) # here we add value in set 'a' ..it also added in set 'b'
print("Original value After add new value of set 'a':",a)
print("Affetced value After add in set 'b':",b)
# If you add anything new element in set 'b' , it will also affect in set 'a'
# Because set 'a' and set 'b' both are accessing same memory
b.add(6)
print("Original value After add new value of set 'b':",b)
print("Affetced value After add in set 'a':",a)
# if you need not affect any changes to copied set means
c=b.copy() # not sharing same memory
print("The value of set 'c' is:",c)
b.add(7) #now here we have add a new element in set 'b'
#it not affect in set 'c'
print("The value of set 'b' is:",b)
print("The value of set 'c' is:",c)
OUTPUT:
Original value of set 'a': {1, 2, 4}
Copied value of set 'b': {1, 2, 4}
Original value After add new value of set 'a': {1, 2, 4, 5}
Affetced value After add in set 'b': {1, 2, 4, 5}
Original value After add new value of set 'b': {1, 2, 4, 5, 6}
Affetced value After add in set 'a': {1, 2, 4, 5, 6}
The value of set 'c' is: {1, 2, 4, 5, 6}
The value of set 'b' is: {1, 2, 4, 5, 6, 7}
The value of set 'c' is: {1, 2, 4, 5, 6}

Python Set Operations:


 Set can be performed mathematical operation such as Union , Intersection,
difference, and symmetric difference.
 Python provides the facility to carry out these operations with operators or methods
Union of Two Set:
 The Union of two sets is calculated by using the pipe() operator.
 The Union of the two sets contains all the items that are present in both sets.

Prg43: To Write a Python program Copy Function of Set Data Type:


a={1,2,3,4}
b={1,2,5,6}
# Difference find using Functions
print("Set of 'a' is:",a)
print("Set of 'b' is:",b)
print("Set 'a' difference of 'b' is:",a.difference(b)) # if set 'a' value is not avialable set 'b' that
is only display
print("Set 'b' difference of 'a' is:",b.difference(a)) #if set 'b' value is not available set 'a' that
is only display

# Difference find using Operators


print("Set 'a'-'b' is:",a-b)
print("Set 'b'-'a' is:",b-a)

# Union find using Functions


print("Set 'a' Union of 'b' is:",a.union(b))
print("Set 'b' Union of 'a' is:",b.union(a))
# Union find using Operators
print("Set 'a'|'b' is:",a|b)
print("Set 'b'|'a' is:",b|a)

# Intersection find using Functions


print("Set 'a' intersection of 'b' is:",a.intersection(b))

# Intersection find using Operators


print("Set 'a' intersection of 'b' is:",a&b)

# Is Disjoint ( No element is common means it return true)


#Is Disjoint ( element is common means it return false)
c={1,2,3,4}
d={5,6,7}
print(" set 'c' isdisjoint of set 'd':",c.isdisjoint(d))
print(" set 'c' isdisjoint of set 'a':",c.isdisjoint(a))

#isSubset
e={1,2,3}
f={1,2,3,4,5}
print("set 'e' issubset of set 'f':",e.issubset(f))
print("set 'e' issubset of set 'b':",e.issubset(b))

#issuperset
g={1,2,3,4,5}
h={1,2}
print(" set 'g'value is avialable in set 'h':",h.issuperset(g))
print(" set 'h'value is avialable in set 'g':",g.issuperset(h))
g.pop() # to remove 1st value of set 'g'
print(" After pop() operation in set 'g':",g)
g.remove(4) # to the value 4 of set 'g'
print(" After remove the value 4 of set 'g':",g)
# Symmetric Different ( it return except common numbers of two sets)
m={1,2,4}
n={1,5,6}
print(" Set 'm' is:",m)
print(" Set 'n' is:",n)
print("symmetric different set 'm' and 'n' is:",m^n) #a.symmetric_difference(n)

OUTPUT:
Set of 'a' is: {1, 2, 3, 4}
Set of 'b' is: {1, 2, 5, 6}
Set 'a' difference of 'b' is: {3, 4}
Set 'b' difference of 'a' is: {5, 6}
Set 'a'-'b' is: {3, 4}
Set 'b'-'a' is: {5, 6}
Set 'a' Union of 'b' is: {1, 2, 3, 4, 5, 6}
Set 'b' Union of 'a' is: {1, 2, 3, 4, 5, 6}
Set 'a'|'b' is: {1, 2, 3, 4, 5, 6}
Set 'b'|'a' is: {1, 2, 3, 4, 5, 6}
Set 'a' intersection of 'b' is: {1, 2}
Set 'a' intersection of 'b' is: {1, 2}
set 'c' isdisjoint of set 'd': True
set 'c' isdisjoint of set 'a': False
set 'e' issubset of set 'f': True
set 'e' issubset of set 'b': False
set 'g'value is avialable in set 'h': False
set 'h'value is avialable in set 'g': True
After pop() operation in set 'g': {2, 3, 4, 5}
After remove the value 4 of set 'g': {2, 3, 5}
Set 'm' is: {1, 2, 4}
Set 'n' is: {1, 5, 6}
symmetric different set 'm' and 'n' is: {2, 4, 5, 6}

Python Dictionary

 Python Dictionary is used to store the data in a Key value pair format.
 The Dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key.
 It is the mutable data-structure
 The Dictionary is defined into element Keys and values
 Keys must be a single element
 Value can be any type such as list , tuple , Integer , etc,.
 In other words, we can say that a dictionary is the collection of key-value pairs where
the value can be any Python object.
 In contrast, the key are the immutable Python object, i.e Number, string, or Tuple

Creating The Dictionary:

 The Dictionary can be created by using multiple key value pairs enclosed with the
curly brackets {}, and each key is separated from its value by the colon (:).

Prg44: To Write a Python program of Dictionary Data Type:


md={"Name":"Krish","age":"31"} # Here Key : values
print("Dictionary Values:",md)
# get() it is display the value of exact key
print("Age is:",md.get("age"))
print("Name is:",md.get("Name"))
# to update any new values of existing key
md["age"]="28"
print(" update Age is:",md.get("age"))

OUTPUT:
Dictionary Values: {'Name': 'Krish', 'age': '31'}
Age is: 31
Name is: Krish
update Age is: 28
Python Function

 Function are the most important aspect of an application.


 A function can be defined as the organized block of reusable code, which can be
called whenever required.
 Python allows us to divided a large program into the basic building block known as a
function.
 The function contains the set of programming statements enclosed by {}.
 A function can be called multiple times to provide reusability and modularity to the
Python program.
 The Function helps to programmer to break the program into the smaller part.
 It organizes the code very effectively and avoids the repetition of the code.
 As the program grows , function makes the program more organized.
 Python provides us various inbuilt functions like range(), print(),although the user
can create its functions, which can be called user defined functions.
 There are mainly Two types of functions
o User Define- function , The user define functions are those define by the user
to perform the specific task.
o Built in Function , The built in functions are those functions that are pre
defined in Python

Advantage of functions in Python:


 Using Functions, we can avoid rewriting the same logic/code again and again in a
program.
 We can call python functions multiple times in a program and anywhere in a
program.
 Reusability is the main achievement of Python functions.
Creating a Function:
 Python provides the def-keyword to define the function.
Def function_name(parameter) :
Function definition
return expression
Function calling:
 In Python , after the function is created .we can call it from another function.
 A function must be defined before the function call, Otherwise the Python
interpreter gives an error.
 To call the function, use the function name followed by the parentheses .
The return statement:
 The return statement is used at the end of the function and returns the result of the
function.
 It terminates the function execution and transfers the result where the function is
called.
 The return statement can’t be used outside of the function.

Prg45: To Write a Python program of Function(Type-1):


# Type-1: Define Function ( No Arguments, No return statement)
def toadd():
a=10
b=20
c=a+b
print("Addition is:",c)
# calling function in the main Program
toadd() # Here we calling function
OUTPUT:
Addition is: 30
Prg46: To Write a Python program of Function(Type-2):
# Type-2: Define Function ( With Arguments, No return statement)
def eligible(n,a): # function with two arguments
if(a>=18):
print(n,"U are Eligible to Vote")
else:
wt=18-a
print(n,"U Just wait for another ",wt," years")

# calling function in the main Program


nam=input("Enter the User Name:")
age=int(input("Enter User Age:"))
eligible(nam,age) # Here we calling funtion
OUTPUT:
Enter the User Name:Krish
Enter User Age:31
Krish U are Eligible to Vote

Prg47: To Write a Python program of Function(Type-3):


# Type-3: Define Function ( With Arguments, With return statement)
def area(rd): # function single arguments
a=3.14*rd*rd
return a # here return the result to called area of the main function
# calling function in the main Program
r=float(input("Enter Radius of the circle:"))
res=area(r) # Here we calling function with passing parameter to user define function
print("Area of Circle is",res)
OUTPUT:
Enter Radius of the circle:2
Area of Circle is 12.56
Default argument:
 Python allows us to initialize the arguments at the function definition.
 If the value of any of the argument is not provided at the time of function call, then
that argument can be initialized with the value given in the definition even if the
argument is not specified at the function call.

Prg48: To Write a Python program of Default argument of Function:


#Default Argument of Function
def printme(name,gen="male"): # function with default arguments
print(" My name is:",name," and my gender is:",gen)
# calling function in the main Program
printme(name="krish") # here we have assign value of name but not assign the gender
OUTPUT:
My name is: krish and my gender is: male

Variable Length Arguments(*args):


 I large projects, sometimes we may not know the number of argument to be passed
in advance. In such cases , Python provides us the flexibility to offer the comma –
separated values which are internally treated as types at the function call. By using
the variable length arguments, we can pass any number of arguments.
 However at the function definition , we define the variable length argument the
*args( star as ) * variable – name.

Prg49: To Write a Python program Variable length(*args):


#variable length *args
def printme(*names):
print("Printing the passed arguments:")
for n in names:
print(n,end=' ' )
# calling function in the main Program
printme("Krish","joshua","isac","rahul","Vishnu")
OUTPUT:
Printing the passed arguments:
Krish joshua isac rahul Vishnu

Prg50: To Write a Python program Values in different order in function:


#values of Different oreder
def simple_int(p,t,r):
print("P is:",p)
return (p*t*r)/100
# calling function in the main Program
print("Simple Interest is:",simple_int(t=10,r=5,p=1900))
OUTPUT:
P is: 1900
Simple Interest is: 950.0
Keyword Argument(**kwdargs)
 Python allows us to call the function with the keyword arguments.
 This kind of function call will enable us to pass the arguments in the random order.
 The name of the arguments is treated as the keywords and matched in the function
calling and definition.
 If the same match is found in the values of the arguments are copied in the function
definition.
 Python provides the facility to pass the multiple keyword arguments which can be
represented as **kwdargs . It is similar as the *args but it store the arguments as the
Dictionary format.
 This type of arguments is useful when we don’t know the name of argument on
advance.
Prg51: To Write a Python program Keyword Argumet(**kwdarg) in function:
#Keyword argument(** kwdargs)
def food(**kwd):
print(kwd)
# calling function in the main Program
food(a="Apple",o="Orange")
food(m="mobile",l="Laptop")
OUTPUT:
{'a': 'Apple', 'o': 'Orange'}
{'m': 'mobile', 'l': 'Laptop'}
Scope Of Variables
 The scope of the variable depend upon the location where the variable is being
declared .
 The variable declared in one part of the program may not be accessible to the other
parts.
Two type of Scope:
1. Global variables
2. Local variables
 The Variable defined outside any function is known to have a global scope, whereas
the variable defined inside a function is known to have a local scope.
Prg52: To Write a Python program For Local Variable:
#Local Variables
def mg():
m="Hello !! "
print(m)
# calling function in the main Program
mg() # here calling function
#print(" Local Variable :",m)# here leads error because local variable can't accessible here
OUTPUT:
Hello !!
Prg53: To Write a Python program For Global Variable:
#Global Variables
def calculate(*args):
s=0 # it is local variable , it can’t access only function
for arg in args:
s=s+arg
print("the sum of local value is:",s)
# calling function in the main Program
s=100 # it is global , we can access anywhere inthe program
calculate(2,3,4) # here calling function
print(" Sum of global Variable is :",s)
OUTPUT:
the sum of local value is: 9
Sum of global Variable is : 100

Python Lambda Functions


 Python Lambda function is known as the anonymous function that is defined without
a name.
 Python allows us to not declare the function in the standard manner, by using the
def keyword
 The anonymous functions are declared by using the lambda keyword.
 However, Lambda functions can accept any number of arguments , but they can
return only one value in the form of expression.
 The anonymous function contains a small piece of code.
 It simulates inline function of C and C++.

Syntax :
lambda arguments : expression
 It can accept any number of arguments and has only one expression.
 It is useful when the function objects are required.
Prg54: To Write a Python program For Lambda Function:

a5=lambda num:num+10 # Here variable a5 act as a function of next code


print(a5(10)) #here we got expression answer with single argument

print(a5(100)) # once again we called lambda function

dip=lambda x:x*10
print(dip(5)) # single argument

dip=lambda x,y:x*10+y # multiple argument


print(dip(7,2))

OUTPUT:
20
110
50
72

Python Exception
 An Exception can be defined as an unusual condition in a program resulting in the
interruption in the flow of the program.
 Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the runtime errors that are
unable to handle to Python script.
 An exception is a Python object that represented an error.
 Python provides a way to handle the exception so that the code can be executed
without any interruption.
 If we do not handle the exception, the interpreter doesn’t execute all the code that
exists after the exception.
 Python has many built in exception that enable our program to run without
interruption and give the output.
 ZeroDivisionError: occurs when a number is divided by Zero
 NameError : it occurs when a name is not found.it may be local or global.
 IdentationError : - If incorrect indentation is given.
 IOError: - It occurs when Input and Output operation fails.

The Problem without handling exception:


 As we have already discussed , the exception is an abnormal condition that halts the
execution of the program.
 Suppose we have two variables a and b , which take the input from the user and
perform the division these values.
 What if the user entered the zero as the denominator?
 It will Interrupt the program execution and through a ZeroDivision Exception.

Prg55: To Write a Python program For Without handling Exception:


a=int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b
d=a+b
print("A+B:",d) # when b as 0 , we can't get the output of Addition
print("a/b=",c)
print(" Without handling exception")
OUTPUT:
Enter a:3
Enter b:0
ZeroDivisionError: division by zero
 The above program is syntactically correct, but it through the error because of
unusual input. That kind of programming may not be suitable or recommended for
the projects because these projects are required uninterrupted execution.
 That’s why an exception – handling plays an essential role in handling these
unexpected exceptions.
 We can handle theses exception using Python exception handler.
Exception Handling in Python:
The try – expect statement:
 If the Python program contains suspicious code that may throw the exception, we
must place the code in the try block.
 The try block must be followed with the except statement , which contains a block of
code that will be executed if there is some exception in the try block.
Syntax
try:
Run code
except Exception-1:
Run this code if an exception occurs
except Exception-2:
Run this code if an exception occurs
The try..finally block:
 Python provides the optional finally statement, which is used with the try statement.
 It is executed no matter what exception occurs and used to release the external
resource.
 The finally block provides a guarantee of the execution.
 We can use the finally block with try block in which we can pace the necessary code,
which must be executed before the try statement throw an exception.
Prg56: To Write a Python program For With handling Exception:
try:
a=int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b
print("Division is:",c)
except:
print("Can't divided by Zero")
finally:
c=a+b
print("Addition is:",c)
print(" With handling exception")
OUTPUT-1:
Enter a:3
Enter b:0
Can't divided by Zero
Addition is: 3
With handling exception
OUTPUT-2:
Enter a:3
Enter b:2
Division is: 1.5
Addition is: 5
With handling exception
Prg57: To Write a Python program To find Type of Exception Using
sys.exc_info() function:
import sys # it is used to catch all exception using this package
a=[2,4,6,'a',8,0]
"""for i in a:
c=2/i # when i reach 2/a that we got error , so we can't division next two element
print(c)"""
for i in a:
try:
c=2/i
print(c)
#b=x # this NameError because we did n't declared
except:
print("Error identify:",sys.exc_info()[0]," Occured")
# This is used to identify what is the type of error and it will shows
OUTPUT:
1.0
0.5
0.3333333333333333
Error identify: <class 'TypeError'> Occured
0.25
Error identify: <class 'ZeroDivisionError'> Occured

User Define Exception


 The Python allows us to create our exceptions that can be raised from the program
and caught using the except clause.
 However , we suggest you read this section after visiting the Python object and
classes.
Raise Exception:
 An exception can be raised forcefully by using the raise clause in Python.
 It is useful in that scenario where we need to raise an exception to stop the
execution of the program.
Prg58: To Write a Python program To Raise user define error message:

# Raise Exception with message


try:
age=int(input("enter the age:"))
if(age<18):
raise ValueError("kindly enter exact age")
else:
print("Age is valid")

except ValueError as e:
print(e)
OUTPUT-1:
enter the age:31
Age is valid
OUTPUT-2:
enter the age:2
kindly enter exact age
Python File Handling
 Till now, we were taking the input from the console and writing it back to the
console to interact with the user.
 Sometimes , it is not enough to only display the data on the console.
 The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console since the memory is volatile.
 It is impossible to recover the programmatically generated data again and again.
 The file handling plays an important role when the data need to be stored
permanently into the file.
 A file is a named location on disk to store related information.
 We can access the stored information(non-volatile) after the program termination.
 In Python , Files are treated in two modes as text or binary .
 The file maybe in the text or binary format, and each line of a file is ended with the
special character.
File Operation:
 Open a file
 Read or write – Performing operation
 Close the file
Writing the File:
 To write some text to a file, we need to open the file using the open method with
one of the following access modes.
o w- it will overwrite the file if any file exists. The file pointer is at the beginning
of the file.
o a- It will append the existing file. The File pointer is at the end of the file. It
created a new file if no file exists.
Steps to open a File :
 To make text file in your specified location ( ex: demo.txt)

Prg59: To Write a Python program For Open File:


# To open a existing file
# str=f.read([no of character])
f=open("D:/Python Tutorial/Python Programs/vishnu.txt","r")
str=f.read() # here read all data from the file
print(str)
f.close()
OUTPUT:
Tiruppur
Prg60: To Write a Python program For Write File:

# To Write a file
f=open("D:/Python Tutorial/Python Programs/vishnu.txt","w") # is stroe only current data
f.write("\n Tirupur")
print(“ Data Stored”)
f.close()
Prg61: To Write a Python program For Append File:
# To Read and Write a file( this not overwrite data on existing file
f=open("D:/Python Tutorial/Python Programs/vishnu.txt","a") # is read data and stroe data
f.write("\n avinashi coimbatore")
print(“ Data Stored”)
f.close()

Python OS Module
Renaming the file:
 The Python OS module enables interacting with the operating system.
 The OS provides the functions that are involved in file processing operations like
renaming , deleting,etc.,
 It provides us the rename() method to rename the specific file to new name.

Prg62: To Write a Python program For rename file using OS module:


import os
os.rename("josh.txt","krish.txt")
print(" Name changed success kindly check your current location of python executing")

OUTPUT:
Name changed success kindly check your current location of python executing
Removing the file:
 The OS module provides the remove() methods which is used to remove the
specified file.

Prg63: To Write a Python program For removing file using OS module:


import os
os.remove("krish.txt")
print(" The file is removed the current location of python executing")
OUTPUT:
The file is removed the current location of python executing

Creating New Directory:


 The mkdir() method is used to create the directories in the current working
directory.

Prg64: To Write a Python program To make Directory using OS module:

import os
os.mkdir("krish")
print(" The directory is created the current location of python executing")

OUTPUT:
The directory is created the current location of python executing
Prg65: To Write a Python program To Display current working directory using
OS module:
import os
print(" Current working directory is :",os.getcwd())

Current working directory is : D:\Python Tutorial\Python Programs


Deleting Directory:
 The rmdir() method is used to delete the specified directory.
 Before Delete you must check the folder is empty .
 If folder not empty means , Python don’t delete that directory

Prg66: To Write a Python program To Delete directory using OS module:

import os
os.rmdir("D:/CA/CCS")
print("deleted")
OUTPUT:
Deleted
Python Module
 A Python module can be defined as a python program file which contain a python
code including Python function, class, or variables.
 In other words we can say that our Python code file saved with the extension(.py) is
treated as the module.
 We may have a run able code inside the Python module.
 Module in Python provides us the flexibility to organize the code in a logical way.
 To use the functionality of one module into another, we must have to import the
specific module.
Example:
 In this example , we will create a module named as dove.py which contains a
function that contains a code to print some message on the console.
 Lets create that module named as

dove.py
def display(name):
print("Hai",name)
 Here, we need to include this module into our main module to call the method
display() defined in the module named file.
Loading the module in our Python Code:
 We need to load the module in our Python code to use its functionality. Python
provides two types of statement as defined below
o The import statement
o The from-import statement
The import statement:
 The Import statement is used to import all the functionality of one module into
antoher.
 Here we must notice that we can use the functionality of any Python source file by
importing that file as the module into another Python source file
 We can import multiple modules with a simple import statement but a module is
loaded once regardless of the number of times it has been imported into our file.
 Hence, if we need to call the function display() defined inthe file dove.py , we have
to import that file as a module into our module.
Example:
Prg67: To Write a Python program To import statement:
import dove
name=input(" Enter user name:")
dove.display(name) # This function access from dove.py
OUTPUT:
Enter user name:krish
Hai krish
The From – import statement:
 Instead of importing the whole module into the namespace, Python the flexibility to
import only the specific attributes of a module this can be done by using from-
import statement.
 Consider the following module named as calculation which contains three functions
as summation , multiple , and divide.

Calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b
def division(a,b):
return a/b

Prg68: To Write a Python program To from-import statement:


from Calculation import summation
# here it will import the summation() - function from Calculation.py
a=int(input(" Enter the value A:"))
b=int(input(" Enter the value B:"))
print(" SUM = ", summation(a,b))
# Here we don't to specify the module name while accessing summation() - method
# if you want to import all method from the calculation you can use (import*)
# If you want to rename module use ( import calculation as calc)
OUTPUT:
Enter the value A:5
Enter the value B:4
SUM = 9
Use dir() function:
 The dir() function return a sorted list of names defined in the passed module. This list
contains all the sub_Modules , Variables and functions defined in this module.

Prg69: To Write a Python program for dir()


import Calculation
l1=dir(Calculation)
print(l1)

OUTPUT:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'division', 'multiplication', 'summation']

Prg70: To Write a Python program Pre Defined Module:


import math
print(" The Pi value is:",math.pi)
print(" The Power value is:",math.pow(2,3))
print(" The Floor value is:",math.floor(10.25201))
print(" The Ceil value is:",math.ceil(10.25201))
print(" The Factorial value is:",math.factorial(5))
OUTPUT:
The Pi value is: 3.141592653589793
The Power value is: 8.0
The Floor value is: 10
The Ceil value is: 11
The Factorial value is: 120

Python OOPS
 Like other general purpose programming language .Python is also an object or/
language since its begins. It allows us to develop application using a object oriented
approach. In Python , we can easily create and use class and obect.
 An Object oriented paradigm is to design the program using class and objects.
 The object is related to real-word entities such as book, house,pencil etc.,
 The OOPS concept focuses on writing the reusable code.
 It is a widespread technique to solve the problem by creating object.

CLASS:
 The class can be defined as a collection of objects.
 It’s a logical entity that has same specific attributes and methods. For example , If
you have an employee class. Then it should contain on attributes and method.
 (i.e) email id, name , age , salary

Object:
 The object is an entity that has state and behaviour it maybe any real-world object
like the mouse, keyboard, chair , table , pen.
 Everything in python is an object and almost everything has attributes and methods.
All functions have a built in attribute _doc_ , which returns the doc string defined in
the function source code.

Method:
 The method is a function that is associated with as object. In Python a method is not
unique to class instance. Any object type can have methods.

Prg71: To Write a Python program Pre Defined Module:


class employee:
_name=""
_age=0
_dob=""
_p=0
_ab=0
_bpay=0
_pds=0
_phr=0
_tot=0
_ot=0
_ad=0
_hra=0
_netsal=0
def person(self): # Here we need to mention one default argument (i.e) self
self.name=input(" Enter Employee name:")
self.age=int(input(" Enter Employee Age:"))
self.dob=input(" Enter Date of Birth:")

def salary(self):
self.p=int(input(" Enter Present:"))
self.ab=30-self.p
self.bpay=int(input(" Enter Basic pay:"))
self.pds=self.bpay/30
self.phr=self.pds/8
self.tot=int(input(" ENter the total ot:"))
self.ot=self.tot*self.phr
self.ad=int(input(" Enter advance paid:"))
if(self.bpay>=8000 and self.bpay<=15000):
self.hra=self.bpay*1.5
elif(self.bpay>15000 and self.bpay<=25000):
self.hra=self.bpay*3.5
else:
self.hra=self.bpay*4.5
self.netsal=self.p*self.pds+self.ot-self.ad
def display(self):
print(" Employee name is:",self.name)
print(" Employee Age is:",self.age)
print(" Employee DOB is:",self.dob)
print(" Employee Basic pay is:",self.bpay)
print(" Employee Per day salary is:",self.pds)
print(" Employee Per Hr salary is:",self.phr)
print(" Employee Total OT is:",self.ot)
print(" Employee Net salary is:",self.netsal)

c1=employee() # here we have creating object for class employee


c1.person()
c1.salary()
c1.display()

OUTPUT:
Enter Employee name:krish
Enter Employee Age:23
Enter Date of Birth:09-02-90
Enter Present:29
Enter Basic pay:15000
ENter the total ot:5
Enter advance paid:100
Employee name is: krish
Employee Age is: 23
Employee DOB is: 09-02-90
Employee Basic pay is: 15000
Employee Per day salary is: 500.0
Employee Per Hr salary is: 62.5
Employee Total OT is: 312.5
Employee Net salary is: 14712.5
Prg72: To Write a Python program String Data Type:
word='HaiIndia'
word2=" Welomes to Tamilnadu "
word3="My age is 31!" # String contains words,numbers,special characters
word4="www.google.com"
# if you want to store a paragraph
para=""" hello chennai welcome
to tirpur city"""
print(" the string of word:",word)
print(" the string of word2:",word2)
print(" the string of word3:",word3)
print(para)
# slicing
print(" 4th index of word2 is:",word2[4])
print(" start with 0th and end with 4th index of word2:",word2[0:4])
# here start with 0 th index end with 4th index ( but it will not print 4th index)
print(" The length of word3:",len(word3))
# strip() - it is used to remove white space of begin and end of sentence
print(" Before strip word2:",word2)
print(" After strip word2:",word2.strip())
print(" Uppercase of word2:",word2.upper())
print(" Lower case of word3:",word3.lower())
print(" Replace for 'Ta' to 'Th' of word2 is:",word2.replace('T','Th'))
# to find some words into a pragraph
print("India is available of word variable:","India" in word)
print("Tamil is available of word variable:","Tamil" in word)
# endswith
print(" The word4 is endwith(.com)?:",word4.endswith('com'))
# startswith
print(" The word4 is endwith(.com)?:",word4.startswith('www'))
# count
print(" How many 'o' is presented in word4 :",word4.count('o'))
# find index of the string in sentence
print("The google index of word4 :",word4.index('google'))
OUTPUT:
the string of word: HaiIndia
the string of word2: Welomes to Tamilnadu
the string of word3: My age is 31!
hello chennai welcome
to tirpur city
4th index of word2 is: o
start with 0th and end with 4th index of word2: Wel
The length of word3: 13
Before strip word2: Welomes to Tamilnadu
After strip word2: Welomes to Tamilnadu
Uppercase of word2: WELOMES TO TAMILNADU
Lower case of word3: my age is 31!
Replace for 'Ta' to 'Th' of word2 is: Welomes to Thamilnadu
India is available of word variable: True
Tamil is available of word variable: False
The word4 is endwith(.com)?: True
The word4 is endwith(.com)?: True
How many 'o' is presented in word4 : 3
The goole index of word4 : 4
Python Constructor
 A Constructor is a special type of method(function),which is used to initialize the
instance members of the class.
 In Cpp or Java, the constructor has the same name as its class, but it treats
constructor differently in Python. It is used to create an object.
 Constructor can be of two types.
o Parameterized Constructor
o Non- Parameterized Constructor
 Constructor definition is executed when we create the object of this class.
 Constructor also verify that there are enough resources for the object to perform
any start-up task.
Creating the constructor in Python:
 In Python , The method the __init__() simulated the constructor of the class.
 This method is called when the class is instantiated.
 It accepts the self- keyword as a first argument which allows accessing the attributes
or method of the class.
 We can pass any number of arguments at the time of creating the class object,
depending upon the __init__() definition .
 It is mostly used to initialize the class attributes. Every class must have a constructor
, even if it simply relies on the default constructor .

Prg73: To Write a Python program For Non-Parameterized constructor :


class student:
stu_name=''
rollno=0
def __init__(self):
self.stu_name="krish"
self.rollno=23
print(" constructor invoked")
def display(self):
print(" student Name:",self.stu_name)
print(" Student rollno:",self.rollno)
ob1=student() # here constructor is invoked that means __init__() will executed
automatically
# If you want to to print name and rollno , you need to call display()-method
ob1.display()
OUTPUT:
Student Name:krish
Student rollno:23
Prg74: To Write a Python program For Parameterized constructor :
class student:
def __init__(self,name,rno):
self.name=name
self.rno=rno
print(" constructor invoked")
def display(self):
print(" student Name:",self.name)
print(" Student rollno:",self.rno)

ob1=student("Krish",101) # constructor with two arguments


ob1.display()
ob2=student("Joshua",102)
ob2.display()
OUTPUT:
constructor invoked
student Name: Krish
Student rollno: 101
constructor invoked
student Name: Joshua
Student rollno: 102
Python Inheritance
 Inheritance is an important aspect of the object oriented paradigm.
 Inheritance provides code reusability to the program because we can use an existing
class to create a new class instead of creating it form scratch.
 In inheritance , the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.
 In this section of the tutorial , we will discuss inheritance in detail.
 In python , a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name.
Single Inheritance:
 A class can inherit multiple classes by mentioning all of them inside the breacket.

Prg75: To Write a Python program For Single Inheritance :


class circum:
r=0
c=0
def circle_circum(self):
self.r=float(input("enter radius of the circle:"))
self.c=3.14*self.r*self.r
class area(circum): # Here it is called as inheritance ( here class area derived from circum)
a=0
def circle_area(self):
self.a=2*3.14*self.r # Here the ‘r’ is accesing from base class of circum
print(" The circum of circle is:",self.c)
print(" The area of circle is:",self.a)
c1=area() # here we don’t need to create object for class circum
c1.circle_circum() # we can access all methods from parent class by using object of child
c1.circle_area()
OUTPUT:
enter radius of the circle:3
The circum of circle is: 28.259999999999998
The area of circle is: 18.84

Multilevel Inheritance:
 Multi-Level inheritance is possible in Python like other object – oriented language.
 Multi-Level inheritance is archived when a derived class inherits another derived
class. There is no limit on the number of levels up to which, the multi-level
inheritance is archived in Python .

Prg76: To Write a Python program For Multilevel Inheritance :


class circum:
r=0
c=0
def circle_circum(self):
self.r=float(input("enter radius of the circle:"))
self.c=3.14*self.r*self.r
class area(circum): # Here 2nd class accessing property of 1st class
a=0
def circle_area(self):
self.a=2*3.14*self.r
class result(area): # here 3rd class can access the property of 2nd class
def display(self):
print(" The circum of circle is:",self.c)
print(" The area of circle is:",self.a)
c1=result()
c1.circle_circum()
c1.circle_area()
c1.display()
OUTPUT:
enter radius of the circle:4
The circum of circle is: 50.24
The area of circle is: 25.12
Python Super-Keyword
 Super – keyword is used to call immediate parent class constructor.
 When we have two constructor one have in Parent class, another one have in child
class , that time compiler get confused to execute the constructor, but it execute
based on priority , so it will execute only child class constructor , so we didn’t get the
property of parent class constructor( because both have __init()__) method. So this
problem done by super keyword
Without Super-Keyword(Prg77) With Super-Keyword(Prg78)
class bike: class bike:
def __init__(self): def __init__(self):
self.speed="70kmph" self.speed="70kmph"
print(" the max speed of bike print(" the max speed of bike
is:",self.speed) is:",self.speed)
class car(bike): class car(bike):
def __init__(self): def __init__(self):
self.speed="180kmph" super().__init__()
print(" the max speed of car self.speed="180kmph"
is:",self.speed) print(" the max speed of car
is:",self.speed)
c1=car() # here the child class c1=car() # here the child class
constructor only print constructor only print
OUTPUT: OUTPUT:
the max speed of car is: 180kmph the max speed of bike is: 70kmph
the max speed of car is: 180kmph
Python Iterator
 In for loop all elements having same memory , if you want to get the element we
need to mention the index number of the variable
 In iterator all elements having separate memory and also we can move the next
element by using next()- function
In For Loop In Iterator [ Prg79]
a=[10,20,30,40,50] a=[10,20,30,40,50,60]
for i in a: b=iter(a)
print(i) print("The First element of list:",next(b))
we got the o/p print("The second element of list:",next(b))
10 # we can also print the list of element by
20 using for loop but now your cursor
30 # moved on 3rd element so you can get
40 element from 3rd element ...
50 for i in b:
print(i)
OUTPUT:
The First element of list: 10
The second element of list: 20
30
40
50
60
Once it will executed ,if you need to run
again means you want to regenerate the
iterator
Python Generator
 Python generator are the functions that return the traversal object and used to
create iterator.
 A Run time creating iterator by user itself
 Generally we have return() – method in all function , this return is used to return the
final result and terminate the existing function , and the result given to called area.
 In Here we are going to use yield() for replacing of return() .
 This yield() – working as a generator
 It traverses the entire items at once(i.e : it call the method only one time , if a
method contains number of time ,it execute all iterator in the method
 The generator can also be an expression in which syntax is similar to the list
comprehension in Python.
Creating Generator:
 It is similar to the normal function defined by the def keyword and uses a yield
keyword instead of return, or we can say that if the body of any function contains a
yield statement .
 It automatically becomes a generator function

Prg80: To Write a Python program For Generator :


def simple():
# for i in range(10):# it execute upto 9
# if (i%2==0):
# yield i """
yield 12
yield 17
# here the simple() - method called only one time
for i in simple(): # it before programs here we only mention list, and range ( this both will
run no of time)
print(i) # Here we have mention method() so , it exectue only one time
OUTPUT:

12 17
Yield vs return
Yield() Return()
 The yield statement is responsible  The return statement returns a
for controlling the flow of the value and terminates the whole
generator function. function and only one return
 It pauses the function execution by statement can be used in the
saving all states and yield to the function
caller. Later it resumes execution
when a successive function is called.
 We can use the multiple yield
statement in the generator
function.

Multiple yield statement with Iterator:


Prg81: To Write a Python program For Generator :
def three():
s1="India"
yield s1 # generator
s2="TamilNadu"
yield s2
s3="Chennai"
yield s3
ob1=three()
print(next(ob1)) # Iterator-1
print(next(ob1)) # Iterator-2
print(next(ob1)) # Iterator-3
OUTPUT:

India
TamilNadu
Chennai
Different between generator function and normal function:
 Normal function contains only one return statement whereas generator function can
contains one or more yield statement
 When the generator functions are called , the normal function is paused
immediately and control transferred to the caller.
 Local variable and their states are remembered between successive calls .
 Stop Iteration exception is raised automatically when the function terminated

Prg82: To Write a Python program For Generator :


# Generator function
def table(n):
for i in range(1,11):
yield n*i
i=i+1
# Main funtion
for i in table(15): # here table(15) called once
print(i)
OUTPUT:

15
30
45
60
75
90
105
120
135
150
Advantage of Generator:
 Generator are memory efficient for a large number of sequence.
 The normal function returns a sequence of the list which crates an entire sequence
in memory before returning the result.
 But generator function calculated the value and pause their execution.
 It resumes for successive call.
 An infinite sequence generator is a great example of memory optimization.

Python Decorator
 Decorator are one of the most helpful and powerful tools in Python.
 These are used to modify the behavior of the function.
 Decorator provide the flexibility to wrap another function to expand the working of
wrapped function, without permanently modifying it.
 In decorators, functions are passed as an argument into another function and then
called inside the wrapper function.
 It is also called meta programming where a part of the program attempts to change
another part of program at compile time.
 Before understanding the Decorator , we need to know some important concepts of
Python.
o Nested function
o Function can return another function
o Function are reference
o Function are parameter
Prg83: To Write a Python program For Nested Function ,Function can return
another Function, Function Reference :
def outer(): # this outer- method
n1=3
def inner(): # this inner- method
n2=6
res=n1+n2
return res # this inner - method return statement
return inner # here we have return reference of inner-method so here value not be
return, return here function
ob1=outer() # here we called outer(0- method so goes on beginning but there
# inner - method will not execute but n1=3 and the reutrn - satement will return inner()-
method
print(" Here the inner - method will execute now:",ob1()) # it's refers to the inner - method
print(" Denoted result:",ob1.__name__)
OUTPUT:
Here the inner - method will execute now: 9
Denoted result: inner

Prg84: To Write a Python program For Function as Parameter :


def fun1():
print(" Welcome to TamilNadu")
def fun2(fun): # here fun-variable will receive the fun1()- method
print(" Hai Kerala:")
fun() # here fun variable called as reference method

fun2(fun1) # here we have function as parameter


OUTPUT:
Hai Kerala:
Welcome to TamilNadu
Decorator:
 Any Python callable object that is used to modify a function or a class.

Prg85: To Write a Python program For Decorator :


def strupper(func): # here it received printstr()
def inner():
str1=func() # Here str1="hi welcome"
return str1.upper() # here str1="HAI WELCOME" goes to called area-2
return inner # here the outer will return the inner method to called area-1
def printstr():
return "hi welcome"
print(printstr()) # here we called printstr()....so here we got reutrn statment as hai
welcome
ob1=strupper(printstr) # here printstr passed as reference so it goes to strupper()-method
# there inner()- method will not execute but that method return inner() - method as
return value
print(ob1()) # here ob1 call inner()-method
# there func- variable receive "hi welcome" and it's stred again in variable str1
# there the variable str1 will convert as Uppercase using upper() - method and
# that return the values to called area(i.e) ob1()

OUTPUT:
hi welcome
HI WELCOME
The another easy way to implement Decorator is :
Prg86: To Write a Python program For Decorator( Easy way) :
def strupper(func):
def inner():
str1=func()
return str1.upper()
return inner
@strupper # here the complier note it is decorator
def printstr():
return "hi welcome"
print(printstr()) # here we are calling printstr()- metho

Decorator with Parameter:


def div(a,b):
return a/b
print("division is:",div(4,0))
 When we tried to run this code the complier leads( Division by zero) error
 We can decorate this code like as following

Prg87: To Write a Python program For Decorator( with parameter) :


def divdec(fun):
def inner(x,y):
if y==0:
return " give value greater than zero"
return fun(x,y)
return inner
@divdec
def div(a,b):
return a/b
print("division is:",div(4,0))
OUTPUT-1:
division is: give value greater than zero

OUTPUT-2:
division is: 2.0

Python Closure
 Function object that remembers values in the enclosing scope even if they are not
present in memory
 We already discussed this topic
Prg88: To Write a Python program For Closure) :
def outer():
msg="Krish joshusa isac"
def inner():
print(msg)
return inner
ob1=outer()
ob1()
OUTPUT:
Krish joshusa isac
Python Thread ( Multiprocessing)
 Thread is a single unit of processing ( Or Small Task)
 Process is nothing a collection of Threads
 Example :
o A program contains no of function
o When we will call that function ( it will execute one by one )
o If 1st function done after that 2nd function get ready to execute in normal
without using Thread
o We can’t run that no of function at the same time as parallel
o That’s why we are going for Thread method
o If we use Thread we can run no of function at the same time that is called as
multiprocessing
Why Use Thread
 Thread plays a significant role in application programming. All the GUI programs and
web servers are threaded together. The main reasons for using threads area:
o Parallel Computation : if any user has a multiprocessor machine, then the
thread can allows doing parallel processing with goal of an increase in
processing speed.
o Standardization : it became a standard approach for all programming
language as it increase programming speed.
o Parallel I/O (input/output) : When we talk about the speed of input & output
, it is comparatively slow in CPU. By placing each I/O operation in multiple
individual thread, programmers can make use of operations done in parallel
with each other & with the computation speed.
o Asynchronous Events: Multiple threaded application can deal with
asynchronous actions.
o For example : in a program , programmers may not know whether the next
action will be to use the mouse or to use the keyboard. By planting a
separate thread for each action.(i.e) two threads both for mouse and
keyboard.
Benefits of Threading:
 For a single process , multiple thread can be used to process and share the same
data-space and can communicate with each other by sharing information.
 They use lesser memory overhead , and hence thry are called lightweight processes.
 A program can remain responsive to input when thread are used.
 Thread can share and process the global variable’s memory.

There are two type of thread available in Python


1. Kernal Level ( In all languages we will do some operation of kernel level ,it means to
interact with OS , and communicate with OS ) or else Os will start some threads in
system) These all are called as kernel level threads
2. User Level ( this is not start by OS ,it is not depending OS , these thead implemented
by User itself )

Some Package of Thread:


 _thread
 Threading

Methods of Thread Class:


 run() – it acts as the entry of the thread.
 Start() – is used for starting the thread by calling the run() – method.
 isAlive() – is used to verify whether the thread still executing or not.
 getName() – is used for returning the name of a thread.
 setName() – is used to set the name of thread.
def a():
count=0
while count<3 :
count=count+1
print(“function A”)
Without Using Thread With Using Thread [ Prg89]
def b(): import _thread # here we are importing
count=0 thread
while count<3 : import time # we are going to use sleep() -
count=count+1 method ... for taking time delay between
print(“function b”) thread while executing threads
a() def a(msg):
b() count=0
OUTPUT: while count<3:

Function A count=count+1

Function A time.sleep(3)

Function A print(msg)

Function B def b(msg):

Function B count=0

Function B while count<3:

 Kindly note in above program the count=count+1

function a() – executed 3 times time.sleep(5)

after that b()- will executed next 3 print(msg)

times . try:

 if you want to run these both _thread.start_new_thread(a,("Thread1",))

method run at the same time , you _thread.start_new_thread(b,("Thread2",))

can use Thread except:


print("error to start thread")
while 1:
pass
OUTPUT:
Thread1
Thread2 # here thread 2 also will execute
Thread1 # simultaneously
Thread1
Thread2
Thread2

Prg90: To Write a Python program For Multi Thread :


import threading
import time
def a(msg,name):
count=0
while count<3:
count=count+1
time.sleep(3)
print(name,msg)
def b(msg,name):
count=0
while count<3:
count=count+1
time.sleep(5)
print(name,msg)
t1=threading.Thread(target=a,args=("India","Thread-1",))
t1.start()
t2=threading.Thread(target=b,args=("Tamilnadu","Thread-2",))
t2.start()
OUTPUT:
Thread-1 India
Thread-2 Tamilnadu
Thread-1 India
Thread-1 India
Thread-2 Tamilnadu
Thread-2 Tamilnadu
Prg91: To Write a Python program For SetName(), getName(),is_alive()
methods in Multi Thread :

import threading
import time
def a(msg,name):
count=0
while count<3:
count=count+1
time.sleep(3)
print(name,msg)
def b(msg,name):
count=0
while count<3:
count=count+1
time.sleep(5)
print(name,msg)
print("Thread 1 is alive ",t1.is_alive())
t1=threading.Thread(target=a,args=("India","Thread-1",))
t1.start()
t1.setName("krish")
t2=threading.Thread(target=b,args=("Tamilnadu","Thread-2",))
t2.setName("Joshua")
t2.start()
print("first thread name is:",t1.getName())
print("Second thread name is:",t2.getName())

OUTPUT:
first thread name is: krish
Second thread name is: Joshua
>>> Thread-1 India
Thread-2 Tamilnadu
Thread-1 India
Thread-1 India
Thread-2 Tamilnadu
Thread-2 Tamilnadu
Thread 1 is alive False

Python Tkinter
 Python provides the standard library Tkinter for creating the graphical user
interface(GUI) for desktop based applications.
 Developing desktop based application with Python is not a complex task.
 An empty Tkinter top-level window can be created by using the following steps.
 Import the Tkinter Module
 Create the main application window
 Add the widgets like labels, buttons , frames , etc., to the window
 Call the main event loop so that the action can take on the user’s computer screen.
Python Tkinter Geometry:
 The Tkinter geometry specifies the method by using which, the widgets are
represented on display.
 The Python Tkinter provides following methods:
o The pack() – method
o The grid() – method
o The place() – method
Python Tkinter pack() – Method:
 The pack() widget is used to organize widget in the block.
 The position widget added to the python application using the pack() method can be
controlled by using various options specified in the method call.
Prg93: To Write a Python program for Frame Using TKinter Package :
from tkinter import* # here we have include all methods of tkinter package
f1=Tk() # here we have creation object for Tk() - class
f1.geometry("500x400") # 1000 width and 400 height of the frame
l1=Label(f1,text="Krish joshua Isac",font=("Comic Sans
Ms",20),bg="red",fg="white",width="500")
l1.pack()
f1.mainloop() # here we are calling mainloop() method from Tk() - class

OUTPUT:
Prg94: To Write a Python program for Button class Using TKinter Package :

from tkinter import* # here we have include all methods of tkinter package
f1=Tk() # here we have creation object for Tk() - class
redbutton=Button(f1,text="Red",fg="red",
activebackground="black",activeforground=”blue”)
redbutton.pack(side=LEFT) # this Button added in left corner of the frame
greenbutton=Button(f1,text="Green",fg="green")
greenbutton.pack(side=RIGHT) # this Button added in Right corner of the frame
bluebutton=Button(f1,text="Blue",fg="blue")
bluebutton.pack(side=TOP) # this Button added in Top corner of the frame
blackbutton=Button(f1,text="Black",fg="black")
blackbutton.pack(side=BOTTOM) # this Button added in Bottom corner of the frame
f1.geometry("500x400") # 1000 width and 400 height of the frame
f1.mainloop() # here we are calling mainloop() method from Tk() - class
OUTPUT:
Prg95: To Write a Python program for Button Event Using TKinter Package :
from tkinter import*
def click_me():
l=Label(f1,text="Welcome krish")
l.pack()
f1=Tk()
f1.geometry("500x400")
b=Button(f1,text="Msg",bg="yellow",fg="red",font=("courier",10),activebackground="black"
,activeforeground="blue",command=click_me)
# in above code command is used to set event of the button
b.pack()
f1.mainloop()

OUTPUT:
Prg96: To Write a Python program for Checkbox Event Using TKinter Package:
from tkinter import*
import tkinter.messagebox as msgbox
f1=Tk()
f1.geometry("500x400")
ck1=IntVar() # here creating variable for checkbox using IntVar()-method
ck2=IntVar()
ck3=IntVar()
def check():
if ck1.get()==1:
msgbox.showinfo(" Hi", "U have selected C Language")
elif ck2.get()==1:
msgbox.showinfo(" Hi", "U have selected JAVA Language")
elif ck3.get()==1:
msgbox.showinfo(" Hi", "U have selected Python Language")
else:
pass
ckbttn1=Checkbutton(f1,text="C",variable=ck1,onvalue=1,offvalue=0,height=2,width=2)
ckbttn2=Checkbutton(f1,text="JAVA",variable=ck2,onvalue=1,offvalue=0,height=2,width=2)
ckbttn3=Checkbutton(f1,text="PYTHON",variable=ck3,onvalue=1,offvalue=0,height=6,width
=6)
btn=Button(f1,text="Click",command=check,width=10)
ckbttn1.pack()
ckbttn2.pack()
ckbttn3.pack()
btn.pack()
mainloop()
OUTPUT:

Prg97: To Write a Python program for Radio Button Event Using TKinter
Package:
from tkinter import*
import tkinter.messagebox as msgbox
f1=Tk()
f1.geometry("500x400")
def male():
msgbox.showinfo("HI","u have select Male")
def female():
msgbox.showinfo("HI","u have select Female")
rb1=Radiobutton(f1,text="Male",command=male,value=1)
rb2=Radiobutton(f1,text="Female",command=female,value=2)
rb1.pack()
rb2.pack()
mainloop()
OUTPUT:

Prg98: To Write a Python program for ListBox Event Using TKinter Package:
from tkinter import*
f1=Tk()
f1.geometry("300x350")
inputvar=StringVar() # here we have create variable for Entry
def delete():
lb.delete(ANCHOR) # it is used to delete at presented selected item in the list
def insert():
Entry(f1,textvariable=inputvar).pack()
lb.insert(3,inputvar.get()) # here the user given input will be stored in inputvar- variable,
the value get from inputvar

Label(f1,text="My Fav Programming Language").pack()


lb=Listbox(f1,width=50,height=10)
lb.insert(1,"C language")
lb.insert(2,"Java")
delbtn=Button(f1,text="Delete",command=delete)
insbtn=Button(f1,text="Insert",command=insert)
lb.pack()
delbtn.pack()
insbtn.pack()
mainloop()

OUTPUT:

Prg99: To Write a Python program for Menu Using TKinter Package:


from tkinter import*
f1=Tk()
menubar=Menu(f1) # Here we are creating object for class Menu with parameter of Tk()
file=Menu(menubar,tearoff=0) # Here we have creating File Menu
file.add_command(label="New") # Here we are creating Menu items
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save As")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit",command=f1.quit) # here we have wrote exit method for
frame
menubar.add_cascade(label="File",menu=file) # here file menu act as parent in menubar
f1.config(menu=menubar) # here we have our menu in frame by using config() - method
like as pack()
mainloop()

OUTPUT:

Prg100: To Write a Python program for Scale(Volume) Controll Using TKinter


Package:
from tkinter import*
def select():
sel="Value="+str(v.get()) # here the value assign in variable sel
label.config(text=sel) # here the value print on label
top=Tk()
top.geometry("200x100")
v=DoubleVar() # to create variable for Scale
sc=Scale(top,variable=v,from_=1, to=100,orient=HORIZONTAL)
# In above orient means alignment of scale
sc.pack(anchor=CENTER)
# in above anchor=center means to set the scale at middle of the frame
btn=Button(top,text="Value",command=select)
btn.pack(anchor=CENTER)
label=Label(top)
label.pack()
mainloop()

OUTPUT:

Prg101: To Write a Python program for Enter Control Using TKinter Package:
from tkinter import*
top=Tk()
top.geometry("400x250")
name=Label(top,text="Name").place(x=30,y=50)
email=Label(top,text="Email").place(x=30,y=90)
password=Label(top,text="Password").place(x=30,y=130)
sbmitbtn=Button(top,text="Submit",activebackground="pink",activeforeground="blue").pla
ce(x=30,y=170)
e1=Entry(top).place(x=80,y=50)
e2=Entry(top).place(x=80,y=90)
e3=Entry(top).place(x=95,y=130)
top.mainloop()
OUTPUT:

Prg102: To Write a Python program for Digital Clock Using TKinter Package:
from tkinter import*
import time
root=Tk()
def tick():
time2=time.strftime('%H:%M:%S') # to get current time and stored in time2
clock.config(text=time2) # to print time2 value on label
clock.after(200,tick) # it used to change time update and again call tick()-method after
200 million seconds
clock=Label(root,font=('Courier',100,'bold'),bg='green') # Digital dream
clock.pack()
tick() # calling function
root.mainloop()
Prg103: To Write a Python program for Adding Two Numbers Using TKinter
Package:
from tkinter import*
def addNumbers():
res=int(e1.get())+int(e2.get())
myText.set(res)
master=Tk()
myText=StringVar()
Label(master,text="First").grid(row=0,sticky=W) # sticky=W is align the text on the center
of lable
Label(master,text="Second").grid(row=1,sticky=W)
Label(master,text="Result").grid(row=3,sticky=W)
result=Label(master,text="",textvariable=myText).grid(row=3,column=1,sticky=W)
e1=Entry(master)
e2=Entry(master)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
b=Button(master,text="Calculate",command=addNumbers)
b.grid(row=0,column=2,columnspan=2,rowspan=2,sticky=W+E+N+S,padx=50,pady=50)
# here padx is for width and pady is height of the frame
master.mainloop()
OUTPUT:

Prg104: To Write a Python program for Login Using TKinter Package:


from tkinter import*
import tkinter.messagebox as msgbox
def addNumbers():
un=e1.get()
pwd=e2.get()
if un=="krish" and pwd=="CADD":
msgbox.showinfo("Login","welcomes you:"+un)
else:
msgbox.showinfo("Login","Invalid User")
master=Tk()
myText=StringVar()
Label(master,text="User Name:").grid(row=0,sticky=W)# sticky=W is align the text on the
center of lable
Label(master,text="Password:").grid(row=1,sticky=W)
e1=Entry(master)
e2=Entry(master,show="*")
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
b=Button(master,text="Login",command=addNumbers)
b.grid(row=0,column=2,columnspan=2,rowspan=2,sticky=W+E+N+S,padx=50,pady=50)#
here padx is for width and pady is height of the frame
master.mainloop()

Prg105: To Write a Python program To Draw Line and Rectangle Using Canvas
Package:
from tkinter import*
root=Tk()
c=Canvas(root,width=600,height=500) # we can draw a line,circle,rectangle,arc by using
canvas frame
c.pack()
c.create_line(0,0,600,500,width=5,fill='red',dash=(50,50))
c.create_line(0,500,600,0,width=5,fill='red',dash=(3,3))
c.create_rectangle(150,120,450,375,fill='yellow',outline='blue',width=5)
root.mainloop()
OUTPUT:

Prg106: To Write a Python program To Cricle(Oval) and Arc Using Canvas


Package:
from tkinter import*

root=Tk()

c=Canvas(root,width=600,height=500) # we can draw a line,circle,rectangle,arc by using


canvas frame

c.pack()

c.create_oval(100,100,300,300,width=5,fill='green')

c.create_arc(100,100,300,300,start=0,extent=200,fill='red',width=5)

root.mainloop()
OUTPUT:

How to Install get-pip.py File From Net:

 Visit the following link


o https://bootstrap.pypa.io/get-pip.py

 Right click on page click save as  choose Location and save it


 Now the get-pip.py will be download
 And take command Prompt
 Type cd ( your download location)
 Now the cmd ready to run
 And type ( Python get-pip.py)
 Then goto python install location and check the get-pip.py in Script -folder
Prg107: To Write a Python program Searching website Box Using Web
Browser Package:
from tkinter import*

import webbrowser # this is used to Open Web browser For Searching URL or web site

root=Tk()

root.title("Search Bar")

def search():

url=enter_box.get()

webbrowser.open(url)

label1=Label(root,text="Enter URL here",font=("Arial",15,"bold"))

label1.grid(row=0,column=0)

enter_box=Entry(root,width=35)

enter_box.grid(row=0,column=1)

btn1=Button(root,text="Search",command=search,bg="blue",fg="white",font=("arial",14,"b
old"))

btn1.grid(row=1,column=0)

root.mainloop()
OUTPUT:

Prg108: To Write a Python


program Table Box Using
tkinter Package:
from tkinter import*

root=Tk()

lst=[('S.No','Name','Location','Age'),

(1,'Krish','Avinashi',31),

(2,'Joshua','Tiruppur',10),

(3,'Isac','Tiruppur',12),

(4,'Madhi','Cbe',31)]

total_rows=len(lst)

total_column=len(lst[1])

for i in range(total_rows):

for j in range(total_column):

e=Entry(root,width=20,fg="blue",font=('Arial',16,'bold'))

e.grid(row=i,column=j)

e.insert(0,lst[i][j])

root.mainloop()
OUTPUT:

Prg109: To Write a Python program Age Calculate Using Date Package:


from tkinter import*

from datetime import date

root=Tk()

root.geometry("700x500")

root.title("Age Calculation App")

#photo=PhotoImage(file="c:\\User\\vijay\download\\new_age.png")

#myimage=Label(image=photo)

#myimage.grid(row=0,column=1)

def calculateage():

today=date.today() # to get current date

birthDate=date(int(yearEntry.get()),int(monthEntry.get()),int(dayEntry.get()))

age=today.year-birthDate.year-((today.month,today.day)<
(birthDate.month,birthDate.day))

Label(text=f"{nameValue.get()} your age is {age}").grid(row=6,column=1)

Label(text="Name").grid(row=1,column=0,padx=90)
Label(text="Year").grid(row=2,column=0)

Label(text="Month").grid(row=3,column=0)

Label(text="Day").grid(row=4,column=0)

nameValue=StringVar()

yearValue=StringVar()

monthValue=StringVar()

dayValue=StringVar()

nameEntry=Entry(root,textvariable=nameValue)

yearEntry=Entry(root,textvariable=yearValue)

monthEntry=Entry(root,textvariable=monthValue)

dayEntry=Entry(root,textvariable=dayValue)

nameEntry.grid(row=1,column=1,pady=10)

yearEntry.grid(row=2,column=1,pady=10)

monthEntry.grid(row=3,column=1,pady=10)

dayEntry.grid(row=4,column=1,pady=10)

Button(text="Calculate Age",command=calculateage).grid(row=5,column=1,pady=10)

root.mainloop()

OUTPUT:
Prg110: To Write a Python program Simple Calculator Using Tkinter Package:
from tkinter import*

m=Tk()

m.title("simple Calculator")

def add():

e3.delete(0,END)

result=int(e1.get())+int(e2.get())

e3.insert(0,result)
def sub():

e3.delete(0,END)

result=int(e1.get())-int(e2.get())

e3.insert(0,result)

def mul():

e3.delete(0,END)

result=int(e1.get())*int(e2.get())

e3.insert(0,result)

def divi():

e3.delete(0,END)

result=int(e1.get())/int(e2.get())

e3.insert(0,result)

def mod():

e3.delete(0,END)

result=int(e1.get())%int(e2.get())

e3.insert(0,result)

def powe():

e3.delete(0,END)

result=int(e1.get())**int(e2.get())

e3.insert(0,result)

def CLS():

e1.delete(0,END)

e2.delete(0,END)

e3.delete(0,END)

c=Canvas(m,width=350,height=400,bg='gray')

c.pack()
l1=Label(m,text='simple calculator',font=('Arial',14,'bold'),bg='yellow')

c.create_window(160,40,window=l1)

l2=Label(m,text='Enter 1st Number:',font=('Arial',12),bg='pink',width=14)

c.create_window(100,100,window=l2)

l3=Label(m,text='Enter 2nd Number:',font=('Arial',12,),bg='pink',width=14)

c.create_window(100,140,window=l3)

l4=Label(m,text='Result',font=('Arial',12,),bg='pink',width=14)

c.create_window(100,180,window=l4)

e1=Entry(m,bd=4)

c.create_window(260,100,window=e1)

e2=Entry(m,bd=4)

c.create_window(260,140,window=e2)

e3=Entry(m,bd=4)

c.create_window(260,180,window=e3)

b1=Button(text="+",command=add,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(40,250,window=b1)

b2=Button(text="-",command=sub,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(80,250,window=b2)

b3=Button(text="*",command=mul,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(120,250,window=b3)

b4=Button(text="/",command=divi,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(160,250,window=b4)

b5=Button(text="%",command=mod,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(200,250,window=b5)

b6=Button(text="^",command=powe,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(240,250,window=b6)
b7=Button(text="CLS",command=CLS,bg='purple',fg='white',font=('Arial',12,'bold'),width=5)

c.create_window(280,250,window=b7)

b8=Button(text="close",command=m.destroy,bg='purple',fg='white',font=('Arial',12,'bold'),
width=5)

c.create_window(160,330,window=b8)

m.mainloop()

OUTPUT:
Prg111: To Convert Pytho file To Exe file by Using Pycharm IDE:
1. Visit the following link
2. https://www.jetbrains.com/pycharm/download/#section=windows
3. Click on Download Of Community
4. Click and install it
5. Take a copy of your Python program and past your wish location
6. Here we are going to make Prg110.py as exe
7. Paste into here ( Ex: D:\Python Tutorial\Pythonexefiles)
8. Right click On Prg110  Edit with Pycharm Coommuntiy edition
9. Wait few minutes ( it loading )
10. If you want to convert this file as exe .. we need to download and install the package
(i.e) pyinstaller
11. How to install the above file using Pycharm IDE
12. Goto File menu  click Settings  click Project:Prg110.py
13. Click python interpreter  click ( + ) icon
14. In search box type ( pyinstaller)
15. When install package .. we must connect the internet and click install package
16. After few minutes we got a message package install success
17. Now you can move your project file location and do the following methods
 Shift + Right click on project location and choose ( Open PowerShell window)
 The window will appear like as following

 Then type like as following in the above window


 Ps:D:\Python Tutorial\Pythonexefiles>pyinstaller Prg110.py ( Enter )
 We want to wait few minutes because it is converting exe file after convert we got
message success like as following
 After
convert we got 3
Folders that is
o _Pycache_
o Build
o Dist
 Out Exe file will be in Dist – folder .. the file name is ( Ex : Prg110)
 Double click on it ... we can execute only without source code

 There a black window will appear on back side , if you want to hide it
 You will convert again like as following method
 Ps:D:\Python Tutorial\Pythonexefiles>pyinstaller –w Prg110.py ( Enter )
 Now the black window will not appear on back side
Prg112: To write a Program Copy youtube video link and paste into Python
Youtube download App Using Pytube and hurry.filesize Package:
 Open Pycharm IDE  Click file  New Project  select Project Location
 Give Project Name Is: youtubedownloader  press ok
 There is a default file name will appear (i.e= main.py)
 Right click on it click new  click Pythonfile  give name as
 ( Ex : youtube.py)
 Then type the following code

from tkinter import*


from pytube import YouTube #this class for youtube downloaded
from hurry.filesize import size # to find the file size for converting readable format
import os # To get current path of download file and displayed it by using OS
root=Tk()
root.geometry("500x500")
root.resizable(0,0)
root.title("Youtube Downloader")
def Download():
url=YouTube(str(link.get())) # here we are getting values from entry box and to
convert as it string format and stored in url-variable
video=url.streams.get_by_resolution("720p") # we know the video quality
360p,480p,720p,1080p …here we are going to mention the video quality using streams

streams.first- for low quality , streams.last for high quality


video.download() # it download your current working directory
video_name=video.title # it is display video file name
video_path=os.getcwd() # it is used to display file location
video_size=size(video.filesize) # it is used to display the total MB of the file
v_name="Video Name is:{}".format(video_name)
v_path="Video Path is {}".format(video_path)
v_size="Video Size is:{}".format(video_size)
Label(root,text="Video Downloaded",font="Arial 8").place(x=180,y=220)
Label(root,text=v_name,font="Arial 8").place(x=10,y=260)
Label(root, text=v_path, font="Arial 8").place(x=10, y=300)
Label(root, text=v_size, font="Arial 8").place(x=10, y=340)
Label(root,text="Youtube video Downloader ",font="Arial 20 bold").pack()
link=StringVar()
Label(root,text="Paste Your Link ",font="Arial 20 bold").pack()
link_entry=Entry(root,width=70,textvariable=link).place(x=32,y=90)
Button(root,text="DOWNLOAD",font="Arial 15 bold ",bg="pale violet
red",padx=2,command=Download).place(x=180,y=150)
root.mainloop()

OUTPUT :

 Open google chrome and visit youtube and search some videos
 Right click on video  click copy video URL
 Open Python Project run the file

 Click download button  Your File will be download your current python running
location (i.e) Project file location
How to install modules in Python using cmd ?
 Make internet connection in laptop
 Open Cmd and type the following command to know list of packages already in your
computer
 C:\Users\ELCOT> pip list
 If you want install any other module?
 C:\Users\ELCOT> pip install tkcalendar
 C:\Users\ELCOT> pip install pyinstaller
 C:\Users\ELCOT> pip install gtts
 C:\Users\ELCOT> pip install numpy
 C:\Users\ELCOT> pip install pytube
 C:\Users\ELCOT> pip install hurry.filesize
 In Python install location there is lib – Folder that means default module
 Site – Package means our installed modules

Prg113: To write a Program To convert Text to Speech App Using gTTS


Package:

from tkinter import*


from gtts import gTTS # It is used make audio file (i.e : WAV file)
import os # To save our output file in our computer by using OS
root=Tk()
def play():
language="en" # here we have mention what the language we are going to get as output
convert=gTTS(text=entry.get(),lang=language,slow=False) # Here gTTS will convert the
text as English audio language file .. slow means download speed...
convert.save("convert.wav") # to save our output file in current working directory
os.system("convert.wav") # to open our output file

lb1=Label(text="Text to speech Convertor",font="bold,30",bg="lightpink")


lb1.grid(row=1,column=1)
entry=Entry(width=45,bd=4,font=14)
entry.grid(row=3,column=1)
btn=Button(text="CONVERT",width="15",pady=10,font="bold,15",command=play,bg="yello
w")
btn.grid(row=4,column=1)
root.title("Text to speech convertor")
root.geometry("500x200")
root.mainloop()

OUTPUT:

 Your file will be saved in Your current working directory .. Your file name will be as
following

 Conver( WAV File ) double click and Play it


Prg114: To write a Program DatePicker Using tkCalendar Package:
from tkinter import*

from tkcalendar import* # calendar() - method avilable in this

from tkinter import messagebox

root=Tk()

def cal_func():

def calval():

messagebox.showinfo("Your date isL",cal.get_date())

top=Toplevel(root) # we want to open a calendar in separate window

cal=Calendar(top,font="Arial 14", selectmode="day",year=2021,month=5,day=14)

# in above statement year will be shown 2021 and 5th month and day is 14

cal.pack(fill="both", expand=True)

btn3=Button(top,text="click me",command=calval) # we are going to select any date of

# calender view that going to display when click the btn3

btn3.pack()

def date_func():

def dateval():

messagebox.showinfo("You select:",ent.get())

top=Toplevel(root)

Label(top,text="select date:").pack(padx=10,pady=10)

ent=DateEntry(top,width=15,background="blue",foreground="red",borderwidth=3)

ent.pack(padx=10,pady=10)

btn4=Button(top,text="Click me",command=dateval)

btn4.pack()

btn1=Button(root,text="Calendar",command=cal_func)

btn2=Button(root,text="DateEntry",command=date_func)
btn1.pack()

btn2.pack()

root.mainloop()

OUTPUT-1:
OUTPUT-2:

Prg115: To write a Program To take sceenshot and save it Using pyautogui


Package:

 Make internet conncetion in your computer and open cmd and type like as following
for install the package (EX: pyautogui)
 Pip install pyautogui

import pyautogui as K

hk=K.screenshot()

hk.save("D:\Python Tutorial\Python Programs\myscreenshot\hk.png")

print("Sucessfully taken screenshot")

OUTPUT:
Prg116: To write a Program For Pie Chart Using matplotlib Package:
import matplotlib.pyplot as k

member=['DMK','ADMK','PJB','MNM','DMDK']

voot=[35,25,13,17,10]

k.pie(voot,labels=member,autopct='%.f')

# in above code labels is used memtion name of the statement

# autopct is used to convert the voot as string

k.show()

OUTPUT-1:
Make change in Code

exp=[0,0,0,0,0.5]

# here the thired value will be separated in pie chart

k.pie(voot,labels=member,autopct='%.f',startangle=90,explode=exp)

# startangle=90 our first name start with 90 degree

k.title(" 2021 Election report")

OUTPUT-2:
Prg117: To write a Program Merge Two Video files Using moviepy Package:
from moviepy.editor import*

c1=VideoFileClip("m2.mp4") # give 5 sec videos ...e

c2=VideoFileClip("m1.mp4")

f=concatenate_videoclips([c1,c2])

f.write_videofile("heenukrish.mp4")

print("success")

OUTPUT:

GO and check the file name heenukrish.mp4 in your current working directory
Prg118: To write a Program Convert Video file to Audio file Using moviepy
Package:
import moviepy.editor as k

ch=k.VideoFileClip('fadded.mp4')

ch.audio.write_audiofile('song1.mp3')

print(" Mp4 to Mp3 converted successfully")

OUTPUT:

Go and check your current directory file ... there the video file will be converted as audio file
the file name is : song1.mp3

Prg119: To write a Program Convert Normal Text to Funky Using pyfiglet


Package:
import pyfiglet

text=input("Enter A word:")

k=pyfiglet.figlet_format(text)

print(k)

OUTPUT:
Prg120: To write a Program Creating QR code for Website Using pyqrcode
Package:
import pyqrcode

url='https://www.youtube.com'

k=pyqrcode.create(url)

# Here you website created as qr code

k.svg('YoutubeQr.svg',scale=10)

# here qr code saves as .svg format and scale means

# height of the qr code is 10

OUTPUT:

The file will be stored in current working directory : The file name is: YoutubeQr.svg
Prg121: To write a Program Creating funny cow image Using cowsay Package:
import cowsay

cowsay.cow(" Hello krish")

cowsay.cheese("Hello Joshua")

OUTPUT:
Prg122: To write a Program Send message through whatsapp web Using
pywhatkit Package:

import pywhatkit

pywhatkit.sendwhatmsg("+919898768026","Good Morning",0,0,1)

print(" Message send success")

Prg123: To write a Program To shutdown, Restart You Pc Using OS Package:


import os

print("1: Shutdown")

print("2: Restart")

print("3: Exit")

command=input("Enter your choice:")

if '1' in command:

os.system('shutdown /s')

if '2' in command:

os.system('shutdown /r')

if '3' in command:

exit()

OUTPUT:

1: Shutdown

2: Restart
3: Exit

Enter your choice:2

Your lab will Restart after 2 minutes

CREATING DATABASE PYTHON TO MYSQL

Step-1 :

 Open MySQL Work Bench  Click Local instance MYSQL80(root)


 User Name : root Password : Krishnan@90 ( While installing Password)
 Query-1 window will appear and type the following queries for creating back end

How to Create New Data Base ?

 create database hk;  select this statement and ( Ctrl + Enter )


 use hk;
Here the data base name is : hk

How to Create New Table ?

 create table krish( ID integer auto_increment primary key, usname varchar(20),


age integer, city varchar(20));

Here the table name is : krish

How to view the table?

 Select *from krish;


 Now in your table will be empty records

How to insert a record in to the table?

 insert into krish(usname,age,city) values ('Joshus',25,'erode');


 in above query we don’t want to mention the ID Field because it’s auto generated
 insert into krish(usname,age,city) values ('issac',19,'salem');
 insert into krish(usname,age,city) values ('rahul',35,'tiruppur');
 insert into krish(usname,age,city) values ('vishnu',28,'cbe');
 insert into krish(usname,age,city) values ('moses',34,'madurai');
 Select *from krish;
 Your table will be like as following
 Minimize the MYSQL database window
 Open Python and type the following code
DBPrg1: To write a Program For Data Base Connectivity Using Python With
MYSQL also Using mysql.connector and tabulate Package:
from tabulate import tabulate

import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")

# here con is object name we can specify any name

# here we are going to connect local system that why gave localhost

# if you want to connect online means you metion IP address replace as localhost

# user="root" it is your MYSQL app user name and password also

# Here hk- is data base name ...

# if you wan to check your data base connceted or not you can use following code

'''--------------------------------------------------------------------

if con:

print("connceted successfully")

else:

print("Not connceted successfully")

-----------------------------------------------------------------------'''

def insert(name,age,city):

res=con.cursor()

sql="insert into krish(usname,age,city) values(%s,%s,%s)"

user=(name,age,city) # convert as tuple

res.execute(sql,user) # here the execute() method to assign the value of exact field

con.commit() # commit() it is affect the changes into the DB

print(" New Record inserted successfully")


'''--------------------Updating Records into DB------------------------'''

def update(name,age,city,id):

res=con.cursor()

sql="update krish set usname=%s,age=%s,city=%s where id=%s"

user=(name,age,city,id)

res.execute(sql,user)

con.commit()

print(" Data Updated successfully")

'''-------------------- Display Records from DB------------------------'''

def select():

res=con.cursor() #Here cursor()-method is to retrieve and store the data in to backend

sql="select ID,usname,age,city from krish"

res.execute(sql)

#result=res.fetchone() # it is used to retrive the top most record of the DB (i.e) First
record

#result=res.fetchmany(2)# it is used to display 2 records or specified no of records

result=res.fetchall() # to display all records but here the record will not print properly ..
we can use tabulate-Package(pip install tabulate)

#print(result) # if you use this the record will print not properly

print(tabulate(result,headers=["ID","NAME","AGE","CITY"]))

# in above code headers means headings , it should be string and tuples()

'''--------------------- Deleting Record from DB-----------------------'''

def delete(id):

res=con.cursor()

sql="delete from krish where id=%s"

user=(id,)
res.execute(sql,user)

con.commit()

print(" Data Delete successfully")

'''------------------------ Main Program------------------------'''

while True: # here we are displaying continues output using while True

print("1: Insert Data")

print("2: Update Data")

print("3: Select Data")

print("4: Delete ")

print("5: Exit")

choice=int(input("Enter Your Choice:")) # here getting choice from User

if choice==1:

name=input("Enter Name:")

age=input("Enter Age:")

city=input("Enter City:")

insert(name,age,city) # Calling insert() - Method

elif choice==2:

id=input("Enter The Id to Modify the Name In DB:")

name=input("Enter Name:")

age=input("Enter Age:")

city=input("Enter City:")

update(name,age,city,id) # calling update()-Method

elif choice==3:

select() # calling Select() - Method

elif choice==4:

id=input("Enter ID to Delete:")
delete(id) # calling Delete() - Method

elif choice==5:

quit() # Calling System method (i.e: quit())

else:

print("Invalid selection pls try Again!!")

'''-------------------------------- End-----------------------''''

OUTPUT-1: Selecting Records Form DB:

OUTPUT-2: Insert Record To DB:


OUTPUT-3: Update Record To DB:

OUTPUT-4: Delete Record To DB:


OUTPUT-4: To View Records In DB:

 Select * from Krish;


DBPrg2: To write a Program To insert Multiple records at same time by using
Python With MYSQL also Using mysql.connector and tabulate Package:
import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")

sql="insert into krish values(%s,%s,%s,%s)"

value=[(7,'Jeni',6,'Avinashi'),(8,'Bharath',10,'annur'),(9,'Leesya',12,'sivakashi')]

# in above statement A list contains no of tuple

cur=con.cursor()

a=cur.executemany(sql,value)

# In above code execuxtemany() - method used to insert no of records at same time

con.commit() # it used to affect our record in existing table of DB

print("Success")

OUTPUT-1: Before Inserting Records To DB:


OUTPUT-2: After Inserting Records To DB:
DBPrg3: To write a Program To Create New Table in DB by using Python With
MYSQL also Using mysql.connector and tabulate Package:

import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")

cur=con.cursor()

sh="show tables" # here the word stored in the variable 'sh'

cur.execute(sh) # here we execute the query using cursor object

result=cur.fetchall() # to retrieve all tables in the DB by using fetchall() - method

#that are stored in the variable of 'result'

# to print all the tables from the DB by using For loop

print(" Before add a New table in to Data base of hk:")

for r in result:

print(r)

q="create table heenu(id int,uname varchar(20),dept varchar(2))"

# here we are created the new table (i.e) heenu

cur.execute(q) # here we execute the query using cursor object

cur.execute(sh)

result=cur.fetchall() # to retrieve all tables in the DB by using fetchall() - method

print(" After add a New table in to Data base of hk:")

for r in result:

print(r)
OUTPUT In Python:

OUTPUT In MySql:
DBPrg4: To write a Program For Login Form creation by using Python With
MYSQL also Using mysql.connector and tabulate Package:
from tkinter import*

from tkinter import messagebox

import mysql.connector

def connection(user,passw): # [2] here it is received usname and password from check() -
method
con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk") # here connecting the DB

query="select id from login where usname=%s and password=%s"

vals=(user,passw) # here usname and password stored as tuple in to the variable 'vals'

cur=con.cursor() # creating object for cursor()-method

cur.execute(query,vals) # executing query using cursor()-method

result=cur.fetchall() # to execute all record

con.close()

return result # if the usname and password match means it return value=1 or else
return value=0 ...[2]

def check(): # [1] here comes your request from login button

u_name=un.get() # getting usname from user

pass_word=pw.get() # getting password from user

data=connection(u_name,pass_word) # here calling connection() -method for checking


usname and password in to the DB [2]

# in above code 'data' variable will receive the value from connection() - method

if len(data)>0: # here the value is above 0 it display welcomes you

messagebox.showinfo(title="hello "+u_name,message=" Welcomes You")

else:

messagebox.showinfo(title="Hello "+u_name,message=" pls Enter correct user")

root=Tk()
un=StringVar()

pw=StringVar()

root.geometry("300x250")

root.title("Login Form")

t=Label(root,text="Login Form",font=('arial',14),bd=15)

t.pack()

form=Frame(root)

form.pack(side=TOP,fill=X)

nameL=Label(form,text="Username:",font=('arial',14),bd=15)

passL=Label(form,text="Password:",font=('arial',14),bd=15)

nameL.grid(row=1,sticky=W) # align at middle of the frame

passL.grid(row=2,sticky=W)

nameE=Entry(form,textvariable=un)

passE=Entry(form,textvariable=pw,show="*")

nameE.grid(row=1,column=2)

passE.grid(row=2,column=2)

login=Button(root,text="Login",command=check) # here we are calling check() - Method [1]

login.pack()

root.mainloop()
OUTPUT-1: Exact User Login

OUTPUT-2: Incorrect User Login


PYTHON TURTLE GRAPHICS

 Turtle toolkit which provides simple and enjoyable way to draw pictures on windows
or screen
 Turtle graphics refers to controlling a graphical entity in a graphics window with x,y
coordinates

Prg124: To write a Program To Draw Any shapes Using turtle Package:


import turtle

krish=turtle.Turtle() # Here creationg object for Turtle() - class

# here 'turtle' is module name

--------------------------------------------------------------- ---------------------------------------------------

OUTPUT

 In above output the mouse point is not a turtle is called as classic


import turtle

krish=turtle.Turtle() # Here creating object for Turtle() - calss

# here 'turtle' is module name

#1]if you want to check which shape is that

print(" "+krish.shape()) # here we got the answer:classic

#2] if you want to change shape you can use following method

krish.shape("turtle")

OUTPUT

#3] if you want to know how many shapes use here

help(turtle.shape)
#4] if you want to change and want to know about shape color

print(krish.color()) # here we got 'black' 'black'

# in above first ' black' is line color another one is turtle color

krish.shape("classic")

krish.color("blue","green")

krish.forward(100)

krish.color("red","green")

krish.setheading(90)

krish.forward(100)

krish.color("green","green")

krish.setheading(180)

krish.forward(100)

krish.color("pink","green")

krish.setheading(270)

krish.forward(100)

OUTPUT:
Prg125: To write
a Program To
Draw Polygon shapes with different angle Using turtle Package:
import turtle

krish=turtle.Turtle()

# generaly turtle home position is (0,0)

krish.forward(100) # Fd meand forward if u give fd(-100) it going to backward

krish.setheading(45)

krish.forward(100)

krish.setheading(90)

krish.forward(100)

krish.setheading(135)

krish.forward(100)

krish.setheading(180)

krish.forward(100)

krish.setheading(225)

krish.forward(100)

krish.setheading(270)
krish.forward(100)

krish.setheading(315)

krish.forward(100)

OUTPUT:

Prg126: To write a Program To Draw Circle with Fill color and different Circle
Methods Using turtle Package:
import turtle

krish=turtle.Turtle()

krish.circle(20) # here circle will come with 20 radius

krish.circle(-50) # here the circle will come clock wise direction

OUTPUT:
krish.circle(100,180) # It makes semi circle(or) Arc

krish.circle(100,steps=3) # It makes Triangle


krish.circle(70,steps=5) # it makes xegon

Prg127: Another Program For fill circle and Any shapes :

import turtle

krish=turtle.Turtle()

krish.color("blue") # your turtle color will be as white

#help(turtle.bgcolor)

'''--------------------Fill Circle----------------'''

krish.begin_fill() # if not mention this you did not get fill

krish.fillcolor("yellow")

krish.circle(100)

krish.end_fill()

'''--------------------Fill Polygon---------------'''

krish.begin_fill()

krish.fillcolor("green")

krish.circle(100,steps=6)
krish.end_fill() # if not mention this you did not get fill also

'''-------------------- Fill Triangle-------------'''

krish.begin_fill()

krish.fillcolor("red")

krish.circle(100,steps=3)

krish.end_fill() # if not mention this you did not get fill also

krish.hideturtle() # your turtle will hide after end this shape

OUTPUT:

Prg128: Draw Square without For Loop Prg129: Draw Square with For Loop
import turtle import turtle
krish=turtle.Turtle() krish=turtle.Turtle()
krish.color("blue") # your turtle color will wn=turtle.Screen()
be as white wn.bgcolor("black")
krish.speed(1) # 0 means fast and 1 is slow
krish.forward(100) and 6 is normal and 3 is slow
krish.left(90) # it goes upward krish.color("blue") # your turtle color will
krish.forward(100) be as blue
krish.left(90) # it goes Left krish.begin_fill()
krish.forward(100) krish.fillcolor("yellow")
krish.left(90) # it goes Downward for i in range(4):
krish.forward(100) krish.forward(200)
krish.left(90)
krish.end_fill()
krish.hideturtle()

OUTPUT: OUTPUT:
Prg130: TO write a Python Program to draw any shapes in any position Using
turtle:

SAMPLE-1 SAMPLE-2
import turtle import turtle
t=turtle.Turtle() t=turtle.Turtle()
t.circle(100) # here we have draw a circle
at home position t.goto(0,-100) # Your Turtle home position
#t.undo() # here the circle will erase like as will move to(0,-100)
restore t.circle(100)
t.right(90 ) # here your turtle will rotate 90
degree
t.forward(100)
t.left(90) # here your will rotate 90 degree
like as ( -> )
t.circle(100)
OUTPUT: OUTPUT:

Another Program for Up() and Down() method using turtle:

import turtle

t=turtle.Turtle()

t.up() # Your turtle line will hide while drawing

t.goto(0,-100) # your turtle will move at 0,-100

t.down() # if u not mention means your turtle path will be hide

t.circle(100)

t.up()

t.goto(100,100) # your turtle line will move at 100,100

t.down()
t.circle(50)

OUTPUT:

Prg131: To write a Python Program to draw a Pattern at any position Using


turtle:( WITHOUT FUNCTION CALL)

import turtle

t=turtle.Turtle()

'''------------------Draw 1st Circle---------'''

t.up()

t.goto(0,-50)

t.down()

t.begin_fill()

t.fillcolor("green")
t.circle(50)

t.end_fill()

t.up()

t.home() # here your turtle will move at 0,0

'''------------------Draw 2nd Circle---------'''

t.goto(150,150)

t.down()

t.begin_fill()

t.fillcolor("orange")

t.circle(50)

t.end_fill()

t.up()

t.home() # here your turtle will move at 0,0

'''------------------Draw 3rd Circle---------'''

t.goto(-150,150)

t.down()

t.begin_fill()

t.fillcolor("blue")

t.circle(50)

t.end_fill()

t.up()

t.home() # here your turtle will move at 0,0

'''------------------Draw 4th Circle---------'''


t.goto(-150,-150)

t.down()

t.begin_fill()

t.fillcolor("red")

# t.circle(50)- here the distance will be different

t.circle(-50) # here clock wise drawing circle

t.end_fill()

t.up()

t.home() # here your turtle will move at 0,0

'''------------------Draw 5th Circle---------'''

t.goto(150,-150)

t.down()

t.begin_fill()

t.fillcolor("yellow")

t.circle(-50)

t.end_fill()

t.up()

t.home() # here your turtle will move at 0,0


OUTPUT:

Prg132: To write a Python Program to draw a Pattern at any position Using


turtle:( WITH FUNCTION CALL)

import turtle

t=turtle.Turtle()

def drawcircle(x,y,color,rad):

t.goto(x,y)

t.down()

t.begin_fill()

t.fillcolor(color)

t.circle(rad)

t.end_fill()

t.up()

t.home()

t.pensize(2)

t.color(“red”)

t.up()

drawcircle(0,-50,"pink",50)
drawcircle(150,150,"cyan",50)

drawcircle(-150,150,"brown",50)

drawcircle(-150,-150,"violet",-50)

drawcircle(150,-150,"skyblue",-50)

OUTPUT:

Prg133: To write a Python Program to draw a Pattern at any position Using


turtle:

import turtle

t=turtle.Turtle()

t.pensize(0.5)

t.color("red")

t.up()

list1=["yellow","red","blue","green"]

t.goto(150,0)

for i in range(4):

t.down()

t.begin_fill()
t.fillcolor(list1[i])

t.circle(50)

t.end_fill()

t.up()

t.bk(100)

OUTPUT:

If change Radius as 100:

If change pensize and turtle color

for i in range(4):

t.down()

t.color(list1[i])

t.pensize(20)

t.circle(100)

t.up()

t.bk(100)

OUTPUT:
Prg134: To write a Python Program to draw a Pattern at any position Using
turtle:

import turtle

t=turtle.Turtle()

list1=["purple","red","orange","blue","green"]

for i in range(200):

t.color(list1[i%5])# here we got index of list

t.pensize(i/10+1)

t.forward(i)

t.left(59)

OUTPUT:

If you change Angle as 45 degree:


If You change angle as 30 degree:

Prg135: To write a Python Program to draw Heart Using turtle:


import turtle

t=turtle.Turtle()

sc=turtle.Screen()

sc.bgcolor("black")

t.color("red")

t.begin_fill()

t.fillcolor("red")

t.left(140)

t.forward(180)

t.circle(-90,200)

t.setheading(60)

t.circle(-90,200)

t.forward(180)

t.end_fill()

t.hideturtle()

OUTPUT:
Prg136: To write a Python Program to draw Google Chrome LOGO Using
turtle:

from turtle import*

from time import sleep

import turtle

t=turtle.Turtle()

#t.Colormode(255)

red=(223,35,35)

green=(75,183,75)

yellow=(252,210,9)

blue=(86,146,195)

r=120

t.speed(2)

t.seth(-150) # angle

t.up()# direction

t.fillcolor("red")

t.begin_fill()

t.fd(r)

t.down()

t.right(90)

t.circle(-r,120)

t.fd(r*3**.5)

t.left(120)

t.circle(2*r,120)

t.left(60)
t.fd(r*3**.5)

t.end_fill()

t.left(180)

t.fillcolor("green")

t.begin_fill()

t.fd(r*3**.5)

t.left(120)

t.circle(2*r,120)

t.left(60)

t.fd(r*3**.5)

t.left(180)

t.circle(-r,120)

t.end_fill()

t.left(180)

t.circle(r,120)

t.fillcolor("yellow")

t.begin_fill()

t.circle(r,120)

t.right(180)

t.fd(r*3**.5)

t.right(60)

t.circle(-2*r,120)

t.right(120)

t.fd(r*3**.5)
t.end_fill()

t.up()

t.left(90)

t.fd(r/20)

t.seth(60)

t.fillcolor("blue")

t.down()

t.begin_fill()

t.up()

#t.goto(0,50)

t.circle(distance(0,115))

t.end_fill()

OUTPUT:
Prg137: To write a Python Program to draw Good Night Using random and
turtle:

import turtle

import random

win=turtle.Screen()

win.setup(width=800,height=600)

win.bgcolor('black')

'''------------------------1st turtle is Moon--------------------'''

moon=turtle.Turtle()

moon.hideturtle()

'''------------------------2nd turtle is Star--------------------'''

star=turtle.Turtle()

star.speed(0)

star.hideturtle()

colors=['red','blue','orange','yellow','magenta','purple','peru','ivory','dark orange']

'''------------------------3rd turtle is Text--------------------'''

text=turtle.Turtle()

text.speed(6)

text.hideturtle()

'''------------------------ Moon Function-----------------------'''

def draw_moon(pos,color):

x,y=pos

moon.color(color)

moon.penup() # like as up()

moon.goto(x,y)

moon.pendown()
moon.begin_fill()

moon.circle(50)

moon.end_fill()

'''-------------------------Draw Star--------------------------------'''

def draw_star(pos,color,length):

x,y=pos

star.color(color)

star.penup()

star.goto(x,y)

star.pendown()

star.begin_fill()

for i in range(5):

star.forward(length)

star.right(144)

star.forward(length)

star.end_fill()

'''----------------------------Draw Text-----------------------------'''

def write_text(color):

text.color(color)

text.penup()

text.goto(-180,-270)

text.pendown()

style=('Arial',50,'normal')

text.write('Good Night',font=style,move=True) # here move=True means underline

'''--------------------------- Random x,y position--------------------------'''


def random_pos():

return (random.randint(-390,390),random.randint(-200,290))

'''--------------------------- Random Length--------------------------'''

def random_length():

return random.randint(5,25)

draw_moon((-300,170),'white')

draw_moon((-278,183),'black') # semi Moon

# in above moon only draw one time

while True:

color=random.choice(colors)

pos=random_pos()

length=random_length()

draw_star(pos,color,length)

write_text(color)

turtle.done()
OUTPUT:
Prg138: To write a Python Program to Establish the connection between
server to client by using Socket Package

Server Side Program:

# Server Side Program

import socket

s=socket.socket() # we are communicate between client and server by using socket

# if u want to establish a connection(or) communication , need to create IP address first

host=socket.gethostname() # here we are getting our lap IP address

# 2nd thing Port Number it can be anything

port=1234

# 3rd thing you want to bind host port then only you can create server

s.bind((host,port))

# 4th We want to listen a client will come to join into our server

s.listen(5) # here 5 seconds

# these all are steps to create TCP connection

# 5th is we want to accept the connection

print("waiting")

while True: # being connection

conn,addr=s.accept() # here we are accepting the address and connection

print(" Got Connection From :",addr) # here we are printing the connection address

conn.send(b'Thank you for connecting with us')

# here conn- our client address will be in this variable

# we sending the response code as byte that’s why putting 'b' before the message

conn.close()
Prg139: To write a Python Program to Establish the connection between
server to client by using Socket Package

Client Side Program:

# Client Side Program

import socket

s=socket.socket()

host=socket.gethostname()

port=1234 # here same port will be given

# Establish the connection

s.connect((host,port)) # here we are calling connect() - the connection went to server and
the server send the message to client

print(s.recv(1024)) # here the message received and print with help of print

s.close()
OUPUT:

Open two cmd window

1. SERVER SIDE
 D:\Python Tutorial\Python Programs>python Prg138.py

Waiting

2. Client SIDE
 D:\Python Tutorial\Python Programs>python Prg139.py
Prg140: To write a Python Program to Creating chat room between server to
client by using Socket,time,sleep Package

Server Side Program:

import time,socket,sys

print("\n welcome to chat room")

print("Intialising.......")

time.sleep(1)

s=socket.socket() # creating socket

host=socket.gethostname() # getting os name and stored into host

ip=socket.gethostbyname(host) # getting my lap IP Address

port=1234 # it can be everything

s.bind((host,port))

print(host,"(",ip,")\n") # here printing our Ip and host name

name=input(str("Enter your name...."))

s.listen(1) # here our server will connect and listen

print("\n waiting for incoming connection")

conn,addr=s.accept() # accept the incoming request

print("\n Received connection from:",addr[0],"(",addr[1])

s_name=conn.recv(1024) # getting request from client that will be byte code

s_name=s_name.decode() # now byte code will be change as string

print(s_name," has connected to chat room") # here we are printing client name

conn.send(name.encode()) # here we are sending our server name to client as encode

while True:

message=input(str("Me:"))

conn.send(message.encode()) # we are sending our message to client

message=conn.recv(1024) # here we are receiving client message as encode


message=message.decode()

print(s_name,":",message)

Prg141: To write a Python Program to Creating chat room between server to


client by using Socket,time,sleep Package

Client Side Program:

import time,socket,sys

print("\n welcome to chat room")

print("Intialising.......")

time.sleep(1)

s=socket.socket()

shost=socket.gethostname()

ip=socket.gethostbyname(shost)

print(shost,"(",ip,")\n")

host=input(str("Enter the server address to connect..."))

name=input(str("Enter your name:"))

port=1234

print("\n Trying to connect to:",host)

time.sleep(1)

s.connect((host,port))

print("\n connected")

s.send(name.encode()) # here client sent their details to server

s_name=s.recv(1024) # here client receive server details as encode

s_name=s_name.decode() # now byte code will be change as string

print(s_name," has connected to chat room") # here we are printing server name

while True:

message=s.recv(1024) # here we are receiving Server message as encode


message=message.decode()

print(s_name,":",message)

message=input(str("Me:"))

s.send(message.encode()) # we are sending our message to client

OUTPUT:

Open two cmd window

1. SERVER SIDE
 D:\Python Tutorial\Python Programs>python Prg140.py
 Welcome to chat room
 Intialising.......
 Lenovo (127.0.0.1)
 Enter Your Name:Krish
 Waiting for Incoming connection
 Received connection from 127.0.0.1
 Heenu has connected to chat room
 Me:Hello Heenu
 Heenu: Hai krish
 Me:How are you Heenu
 Heenu: I am fine krish, what about you krish
 Me:i am too good!!!
 Heenu : Ok krish bye....have a nice day!!!
 Me: Ok Heenu ....have a nice day too !!!
 Heenu: bye....
 Me: take care!!!
2. CLIENT SIDE
 D:\Python Tutorial\Python Programs>python Prg141x.py
 Welcome to chat room
 Intialising.......
 Lenovo (127.0.0.1)
 Enter the Server address to Connect .... 127.0.0.1
 Enter Your Name: Heenu
 Trying to connect to :127.0.0.1
 Connected
 Krish has connected to chat room
 Krish: Hello Heenu
 Me: hai krish
 Krish: how are you Heenu
 Me: i am fine krish, what about you
 Krish: i am too good!!!
 Me: ok krish bye.... have a nice day!!!
 Krish : ok Heenu....have a nice day too!!!
 Me.bye.....
 Krish: take care !!!

Prg142: To write a Python Program to Creating Registration Form by using
tkinter and Datetime and date Package

from tkinter import*

from tkcalendar import DateEntry

from tkinter import messagebox as mb

import datetime

import pycsv

root=Tk()

root.geometry("520x540")

root.title("Registration Form")

root.configure(background='gray')

def msg():

course=cvar.get()

gender=rvar.get()

if(gender==1 or gender==2):

if(e1.index("end")==0):

mb.showwarning('Missing Details','Enter Your Name')

elif(e2.index("end")==0):

mb.showwarning('Missing Details','Enter Your E-mail Id')

elif(e3.index("end")==0):

mb.showwarning('Missing Details','Enter Your Contact Number')

else:

mb.showinfo('Success','Registration done Successfully for the course:'+course)

else:

mb.showinfo('Missing Details','Enter Your Gender')


def save():

g=rvar.get()

course=cvar.get()

db=dob.get_date()

d=db.strftime('%d/%m/%Y')# convert as string

now=datetime.datetime.now()

if(g==1):

gender='male'

else:

gender='female'

s='\n'+now.strftime("%d-%m-
%Y%H:%M")+'\t'+e1.get()+'\t'+e2.get()+'\t'+e3.get()+'\t'+d+'\t'+gender+'\t'+course

f=open(('regdetails.xls'),'a')

f.write(s)

f.close()

def saveinfo():

save()

msg()

'''-----------------------------------------Labels Creation-------------------------------------------------'''

l0=Label(root,text="Course Registration Form",width=25,font=("Times New


Roman",20,"bold"),bg='blue',fg='white')

l0.place(x=70,y=50)

l1=Label(root,text="Full Name:",width=20,font=("Times New


Roman",12,"bold"),anchor="w",bg='gray')
l1.place(x=70,y=130) # Anchor is used to define where text is position relative to a
reference point

e1=Entry(root,width=30,bd=2)

e1.place(x=240,y=130)

l2=Label(root,text="E-mail:",width=20,font=("Times New
Roman",12,"bold"),anchor="w",bg='gray')

l2.place(x=70,y=180)

e2=Entry(root,width=30,bd=2)

e2.place(x=240,y=180)

l3=Label(root,text="Contact No:",width=20,font=("Times New


Roman",12,"bold"),anchor="w",bg='gray')

l3.place(x=70,y=320)

e3=Entry(root,width=30,bd=2)

e3.place(x=240,y=320)

l4=Label(root,text="DOB:",width=20,font=("Times New
Roman",12,"bold"),anchor="w",bg='gray')

l4.place(x=70,y=230)

l5=Label(root,text="Gender:",width=20,font=("Times New
Roman",12,"bold"),anchor="w",bg='gray')

l5.place(x=70,y=280)

'''----------------------------------------------- Date Picker Creation------------------------------------'''

dob=DateEntry(root,width=27,background='brown',forground='white',date_pattern='dd/m
m/Y',borderwidth=3)

dob.place(x=240,y=230)

'''---------------------------------------------- Radio Button creation ----------------------------------'''

rvar=IntVar()

r1=Radiobutton(root,text="Male",variable=rvar,value=1,font=("Times New
Roman",12),bg='grey')

r1.place(x=235,y=280)
r2=Radiobutton(root,text="Female",variable=rvar,value=2,font=("Times New
Roman",12),bg='grey')

r2.place(x=315,y=280)

'''------------------------------------------------ Dropdown Box Creation---------------------------------'''

cvar=StringVar()

cvar.set("Select Course")

option=("Python","Java","C","CPP")

o=OptionMenu(root,cvar,*option)

o.config(font=("Times New Roman",11),bd=3)

o.place(x=240,y=365,width=190)

'''------------------------------------------------Button and Submit Creation-----------------------------'''

b1=Button(root,text="Submit",command=saveinfo,width=15,bg='green',fg='white',font=("Ti
mes New Roman",12,"bold"))

b1.place(x=120,y=440)

b2=Button(root,text="Cancel",command=root.destroy,width=15,bg='maroon',fg='white',fon
t=("Times New Roman",12,"bold"))

b2.place(x=320,y=440)

root.mainloop()
OUTPUT:
Prg143: To write a Python Program to Creating Student Report by using
Mysql with tkinter Package

from tkinter import*

import tkinter.messagebox as MessageBox

import mysql.connector

from tkinter import simpledialog

root=Tk()

con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")

total=StringVar()

ag=StringVar()

ans=StringVar()

r=StringVar()

n=StringVar()

s=StringVar()

t=StringVar()
e=StringVar()

m=StringVar()

root.geometry("600x500")

root.title("Student Management System")

def result():

r=e1.get()

n=e2.get()

s=e3.get()

t=float(e4.get())

e=float(e5.get())

m=float(e6.get())

tot=t+e+m

total.set(tot)

a=float(tot/3)

ag.set(a)

total.get()

ag.get()

ans.get()

if(t>=35 and e>=35 and m>=35):

ans.set("PASS")

else:

ans.set("FAIL")

def insert():

r=e1.get()

n=e2.get()
s=e3.get()

t=str(e4.get())

e=str(e5.get())

m=str(e6.get())

total=str(e7.get())

ag=str(e8.get())

ans=str(e9.get())

res=con.cursor()

sql="insert into student(rno,sname,std,tam,eng,mat,tot,aveg,res)


values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"

user=(r,n,s,t,e,m,total,ag,ans) # convert as tuple

res.execute(sql,user) # here the execute() method to assign the value of exact field

con.commit() # commit() it is affect the changes into the DB

MessageBox.showinfo("Note","Record inserted successfully")

e1.delete(0,'end')

e2.delete(0,'end')

e3.delete(0,'end')

e4.delete(0,'end')

e5.delete(0,'end')

e6.delete(0,'end')

e7.delete(0,'end')

e8.delete(0,'end')

e9.delete(0,'end')

con.close()

def delete():
res=con.cursor()

r=simpledialog.askstring("Delete","Pls enter the RollNo Which u want to delete:")

#MessageBox.showinfo("Note"," R u Sure You want to delete The rollno:"+r)

sql="delete from student where rno=%s"

user=(r,)

res.execute(sql,user)

con.commit()

MessageBox.showinfo("Note","Record Deleted successfully")

e1.delete(0,'end')

def update():

res=con.cursor()

MessageBox.showinfo("Note","You can only modify name and std ")

r=e1.get()

n=e2.get()

s=e3.get()

sql="update student set sname=%s,std=%s where rno=%s"

user=(n,s,r)

res.execute(sql,user)

con.commit()

MessageBox.showinfo("Note","Record Updated successfully")

def search():

res=con.cursor()

e1.delete(0,'end')

e2.delete(0,'end')
e3.delete(0,'end')

e4.delete(0,'end')

e5.delete(0,'end')

e6.delete(0,'end')

e7.delete(0,'end')

e8.delete(0,'end')

e9.delete(0,'end')

r=simpledialog.askstring("Search","Pls enter the RollNo Which u want to Search:")

sql="select *from student where rno="+r

res.execute(sql)

rows=res.fetchall()

for row in rows:

e1.insert(0,row[0])

e2.insert(0,row[1])

e3.insert(0,row[2])

e4.insert(0,row[3])

e5.insert(0,row[4])

e6.insert(0,row[5])

e7.insert(0,row[6])

e8.insert(0,row[7])

e9.insert(0,row[8])

#con.close()

def clear():

r.set("")

total.set("")
ag.set("")

ans.set("")

n.set("")

s.set("")

t.set("")

e.set("")

m.set("")

rno=Label(root,text='Enter RollNo:',font=('arial',10,'bold'))

rno.place(x=80,y=30)

e1=Entry(textvariable=r)

e1.place(x=280,y=30)

sname=Label(root,text='Enter Student Name:',font=('arial',10,'bold'))

sname.place(x=80,y=80)

e2=Entry(textvariable=n)

e2.place(x=280,y=80)

std=Label(root,text='Enter STD:',font=('arial',10,'bold'))

std.place(x=80,y=130)

e3=Entry(textvariable=s)

e3.place(x=280,y=130)

tam=Label(root,text='Enter Tamil Mark:',font=('arial',10,'bold'))

tam.place(x=80,y=180)
e4=Entry(textvariable=t)

e4.place(x=280,y=180)

eng=Label(root,text='Enter Eng Mark:',font=('arial',10,'bold'))

eng.place(x=80,y=230)

e5=Entry(textvariable=e)

e5.place(x=280,y=230)

mat=Label(root,text='Enter Maths Mark:',font=('arial',10,'bold'))

mat.place(x=80,y=280)

e6=Entry(textvariable=m)

e6.place(x=280,y=280)

tot=Label(root,text='Total Mark is:',font=('arial',10,'bold'))

tot.place(x=80,y=330)

e7=Entry(textvariable=total)

e7.place(x=280,y=330)

avg=Label(root,text='Average is:',font=('arial',10,'bold'))

avg.place(x=80,y=380)

e8=Entry(textvariable=ag)

e8.place(x=280,y=380)

res=Label(root,text='Result is:',font=('arial',10,'bold'))

res.place(x=80,y=430)

e9=Entry(textvariable=ans)
e9.place(x=280,y=430)

b1=Button(root,text="Result",command=result,width=10,bg='green',fg='white',font=("Time
s New Roman",12,"bold"))

b1.place(x=450,y=30)

b2=Button(root,text="Insert",command=insert,width=10,bg='maroon',fg='white',font=("Tim
es New Roman",12,"bold"))

b2.place(x=450,y=90)

b3=Button(root,text="Update",command=update,width=10,bg='maroon',fg='white',font=("T
imes New Roman",12,"bold"))

b3.place(x=450,y=150)

b4=Button(root,text="Delete",command=delete,width=10,bg='maroon',fg='white',font=("Ti
mes New Roman",12,"bold"))

b4.place(x=450,y=215)

b5=Button(root,text="Search",command=search,width=10,bg='maroon',fg='white',font=("Ti
mes New Roman",12,"bold"))

b5.place(x=450,y=275)

b6=Button(root,text="Clear",command=clear,width=10,bg='maroon',fg='white',font=("Time
s New Roman",12,"bold"))

b6.place(x=450,y=335)

b7=Button(root,text="Exit",command=root.destroy,width=10,bg='maroon',fg='white',font=(
"Times New Roman",12,"bold"))

b7.place(x=450,y=395)
root.mainloop()

OUTPUT-(Find Result)

OUTPUT-(Insert Record)
OUTPUT-(Insert Record In MYSQL)
OUTPUT-(Update Record )

OUTPUT-(Update Record In MYSQL )

OUTPUT-(Delete Record )
OUTPUT-(Delete Record In MYSQL )
OUTPUT-(Search Record )
DJANGO

How To Install Django?

 Open Cmd-window with internet connection on your PC and type like as following
 Pip install django
 After few minutes you got successfully installed

How to Check Django is Installed or not?

 Django-admin

Available subcommands:

[django]

check

compilemessages

createcachetable

dbshell

diffsettings

dumpdata

flush

inspectdb

loaddata

makemessages

makemigrations

migrate

runserver

sendtestemail

shell
showmigrations

sqlflush

sqlmigrate

sqlsequencereset

squashmigrations

startapp

startproject

test

testserver

Steps to create web ?


 If you want to create web , first you should create project folder , do like as
following
 Open cmd  and open your project location like as below
 D:\Python Tutorial\Python Programs\Python webapps

Steps to create project?

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject Prg1

(in above code ( Prg1) – Folder will be created in current running directory )

 There is a python file will be available (i.e : manage)


 This manage file will created automatically
 Command line utility which allows us to interact with the project in various ways
and also used to manage an application that we will see later.
 Again the nested folder available in that (Prg1))
 There is 4 – Python files available
 The first file name is ( _init_ )- is this empty file that tells to the python that this
directory should be considered as a python package.
 The second File name is ( settings ) – this file used to configure application settings
such as database connection, static files linking etc.,
 The third file name is ( urls ) – the file contains the listed URLs of the application.
In this file, we can mention the URLs and corresponding actions to perform the
task and display the view.
 The fourth file name is ( wsgi) – It is an entry-point for WSGI- compatible web
server Django project.
Steps to run project?

D:\Python Tutorial\Python Programs\Python webapps>cd Prg1

D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py runserver

 Kindly note something files run on your Cmd don’t close it


 Kindly note your project name (i.e : Prg1.settings)
 Kindly note Your server name is (i.e : http://127.0.0.1:8000)
 Open your Goole chrome browser and type the address like as following
 Localhost:8000 (or) 127.0.0.1:8000
Steps to create Apps?
D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py runserver

 In above output we need fix , if you not fix it we can’t manage the data base so you
want to fix that 18 unapplied migration , how to do?

D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py migrate


 Now we got sqlite file , in this file contains the needed tables of data base
connectivity

How to create App?

D:\Python Tutorial\Python Programs\Python webapps\Prg1>python manage.py startapp myapp1

 Now the myapp1 – folder will be created in Prg1


 In myapp1- folder There is 6 files available
o _init_
o Admin(Admin contains related of administrative ,register your models files )
o Apps( it contains app name and configurations )
o Models ( creating collection of models )
o Test( test your apps by using test)
o Views( UI – configuration , it is display the app)

How to create Administrative ?

D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py runserver

 Now your server get ready run the administrative config then type like as following
in Google chrome address bar

Ex : localhost:8000/admin

 It asking user name and password of Django admin but we did not mention the
user name and password while installing Django , so how to set user name and
password of Django , do the following details

D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py createsuperuser

User name(Leave blank to use ‘elcot’) : Heenukrish

E-mail address : it is optional you can leave it


Password : ( it is not showing ****)

Password (again) :

Superuser created successfully ......

D:\Python Tutorial\Python Programs\Python webapps\ Prg1>python manage.py runserver

 Now your server get ready run the administrative config then type like as following
in Google chrome address bar

Ex : localhost:8000/admin

 Now your administrative account created successfully , now the admin site will be
like as following
Prg1: To write a web Program using Django Package

 Open Your myapp1 folder from Prg1


 D:\Python Tutorial\Python Programs\Python webapps\Prg1\myapp1>
 Open views.py – file and type the code like as following

Views.py
from django.shortcuts import render

from django.http import HttpResponse

def sayHello(request):

return HttpResponse(" Hai krish joshua isac")

We should mention how many Apps available in our project ?

 Open Your Prg1 folder from Prg1


 D:\Python Tutorial\Python Programs\Python webapps\Prg1\Prg1>
 Open settings.py – file and type the code like as following

Settings.py

 Under Application definition section we want to mention our Apps name like as
following

# Application definition

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

' myapp1',

We should mention URLs in our project ?

 Open Your Prg1 folder from Prg1


 D:\Python Tutorial\Python Programs\Python webapps\Prg1\Prg1>
 Open urls.py – file and type the code like as following

urls.py
 Under url patterns section we want to mention our url name like as following
from django.contrib import admin

from django.urls import path

from myapp1.views import sayHello # here we have import 'sayHello' - method from
views.py in myapp1-apps folder

urlpatterns = [

path('admin/', admin.site.urls),

path('www.krishjoshuaisac.com',sayHello) # here 'www.krishjoshuisac.com’ is URL


name and sayHello is method name inside of views.py

Now start the server?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg1>python manage.py runserver

 Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.krishjoshuaisac.com

OUTPUT:

Prg2: To write For HTML Templates using Django Package

Steps To create a New Project ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject Prg2

Steps To create a New App ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg2>python manage.py migrate

D:\Python Tutorial\Python Programs\Python webapps\Prg2>python manage.py startapp myapp2

Now the app will be created in the folder of Prg2

Steps To create a HTML File ?

 Open cmd-window and make a directory like as your wish


 Kindly note the directory should be created in Prg2-folder

D:\Python Tutorial\Python Programs\Python webapps\Prg2>md templates

Now the templates – directory will be created in the folder of Prg2

Create HTML file in Templates Folder ?

 Open Notepad App and type the following code

Hello.html

<html>

<title>Heenu Krish</title>

<body bgcolor="green" text="white">

<font face="Arial"></center>

KRISH JOSHUA ISSAC

</center>

</font>

</body>

</html>

 Press Ctrl +s and chose your project location like as following


D:\Python Tutorial\Python Programs\Python webapps\Prg2\templates

File name : Hello.html  click save

How to insert This HTML file into Django server ?

 Open Your myapp2 folder from Prg2


 D:\Python Tutorial\Python Programs\Python webapps\Prg2\myapp2>
 Open views.py – file and type the code like as following

Views.py
from django.shortcuts import render

from django.http import HttpResponse

def sayHtml(request):

return render(request,'Hello.html') # when we will use Template , That time we need to


use render()-method

Settings.py

 Under Application definition section we want to mention our Apps name like as
following

# Application definition

import os

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

' myapp2',

 Under Template section we want to mention our Template name like as following
TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

DIRS': [os.path.join(BASE_DIR,'templates')],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

urls.py
 Under url patterns section we want to mention our url name like as following

from django.contrib import admin

from django.urls import path

from myapp2.views import sayHtml # here we have import 'sayHtml' - method from
views.py in myapp2-apps folder

urlpatterns = [

path('admin/', admin.site.urls),

path('www.heenukrish.com',sayHtml) # here 'www.heenukrish.com’ is URL name and


sayHtml is method name inside of views.py

Now start the server?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg2>python manage.py runserver

 Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.heenukrish.com

OUTPUT:
How to insert Dynamic content in HTML ?

 Open Your myapp2 folder from Prg2


 D:\Python Tutorial\Python Programs\Python webapps\Prg2\myapp2>
 Open views.py – file and type the code like as following

Views.py

from django.shortcuts import render

from django.http import HttpResponse

def sayHtml(request):

s=input("enter your name:")

return render(request,'Hello.html',{'name':s})

Create HTML file in Templates Folder ?

 Open Notepad App and type the following code

Hello.html

<html> <title>Heenu Krish</title>

<body bgcolor="green" text="white">

<font face="Arial"></center>

KRISH JOSHUA ISSAC

<h1> Hello:{{name}} </h1>

</center>

</font>
</body>

</html>

 Press Ctrl +s and chose your project location like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg2\templates

File name : Hello.html  click save

Now start the server?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg2>python manage.py runserver

 Open google chrome and type the URL address like as following

127.0.0.1:8000/www.heenukrish.com

You page still loading because we did not give any name so open cmd while loading web
page
Prg3: To write a Program For Creating Multiple URls with Templates using
Django Package

Steps To create a New Project ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject Prg3

Steps To create a New App ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg3>python manage.py migrate

D:\Python Tutorial\Python Programs\Python webapps\Prg3>python manage.py startapp myapp3

Now the app will be created in the folder of Prg3

Steps To create a HTML File ?


 Open cmd-window and make a directory like as your wish
 Kindly note the directory should be created in Prg3-folder

D:\Python Tutorial\Python Programs\Python webapps\Prg3>md templates

Now the templates – directory will be created in the folder of Prg3

Create HTML file in Templates Folder ?

 Open Notepad App and type the following code

Home.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Home Page</title>
</head>

<body bgcolor="red">

<font face="Arial" color="yellow" size=6><center>

<br><br>Welcome To Home Page<br><br><br>

</font></center>

<font color="cyan">

<h2>

<UL>

<li> About Us</li>

<li> Course Details</li>

<li> Contact Us</li>

</UL>

<marquee bgcolor="white">

<font color="green">

HOME PAGE !!!

</marquee>

</body>

</html>

Login.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Login Page</title>

</head>

<body bgcolor="red">
<font face="Arial" color="white" size=6><center>

<br><br>Welcome To Login Page<br><br><br>

</font><form name="fm1">

<table border=5 bordercolor="yellow">

<tr>

<td><font color="white">Enter User Name:</td>

<td><input type="text" name="t1"></td>

</tr>

<tr>

<td><font color="white">Enter Password:</td>

<td><input type="password" name="t2"></td>

</tr>

<tr>

<td colspan=2 align="center"><input type="button" name="b1" value="Login"></td>

</tr>

</table>

</center>

<br><br><br>

<marquee bgcolor="pink">

<font color="black" size=5>

Login Page !!!

</marquee>

</body>

</html>
How to insert This HTML file into Django server ?

 Open Your myapp2 folder from Prg3


 D:\Python Tutorial\Python Programs\Python webapps\Prg3\myapp3>
 Open views.py – file and type the code like as following

Views.py
from django.shortcuts import render

from datetime import datetime

from django.http import HttpRequest,HttpResponse

def home(request):

return render(request,'Home.html')

def login(request):

return render(request,'Login.html')

def add(request,n1,n2):# here we are going to receive 3 arguments from the user

s=n1

n=n2

a=s+n

return HttpResponse(f" N1 is: {s}"+f"<br>" + f"N2 is:{n}"+f"<br>"+f"Adding of two number


is:{a}")

Settings.py

 Under Application definition section we want to mention our Apps name like as
following

# Application definition

import os

INSTALLED_APPS = [
'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

' myapp3',

 Under Template section we want to mention our Template name like as following

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

DIRS': [os.path.join(BASE_DIR,'templates')],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

]
urls.py

 Under url patterns section we want to mention our url name like as following

from django.contrib import admin

from django.urls import path

from myapp3.views import home,login,add

urlpatterns = [

path('',home,name='home'),# Here by default the Home page will load

path('www.login.com',login,name='login'),

path('add/<int:n1>/<int:n2>',add,name='add') # here we have mention two integer


arguments

Now start the server?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg2>python manage.py runserver

 Open google chrome and type the URL address like as following

127.0.0.1:8000 press enter .... Here the default Home page will be appear
In address Bar type ( 127.0.0.1:8000/www.login.com)
In address Bar Type (127.0.0.1:8000/add/90/30)

Prg4: To write a Program For Creating Database Connectivity using Models in


Django and mysql Package
Steps To create a New Project ?

 Open cmd – window and type like as following


 Pip install mysql

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject Prg4

Steps To create a New App ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py migrate

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py startapp myapp4

Now the app will be created in the folder of Prg4

Steps To create a New Project ?

 Open MySQL work bench and create a Database

Example : create database Heenu

 Open seeting.py like as following path

D:\Python Tutorial\Python Programs\Python webapps\Prg4\Prg4

Settings.py

 Under Database section we want to mention our Database name like as following

# Database

# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {

'default': {

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

'NAME':'Heenu',
'USER':'root',

'PASSWORD':'Krishnan@90',

'HOST':'localhost',

'PORT':'3306'

Steps To create MYSQL use as DB in Django ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py migrate


Now all the table will insert into our database table in Mysql

How to add a new table in Mysql using django?

 Open the location like following in Python IDE

D:\Python Tutorial\Python Programs\Python webapps> Prg5>myapp4

models.py

from django.db import models

class Employee(models.Model):

eid=models.CharField(max_length=20) # here 'eid' - columnname

ename=models.CharField(max_length=50)

econtact=models.CharField(max_length=50)

def __str__(self):

return slef.ename

class Meta: # we are going to map the above class name as table name

db_table="employee" # here the table name is 'employee'


D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py makemigrations

Now the model will be added into our project but the table will not added into Mysql , so
we need to migrate again like as following ‘

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py migrate

Now the table will be added into Mysql

Steps To Add the above Mysql Table(employee) Into Admin Page ?


 Open the location like following in Python IDE

D:\Python Tutorial\Python Programs\Python webapps> Prg5>myapp4>

admin.py

from django.contrib import admin

from myapp4.models import Employee

# Register your models here.

admin.site.register(Employee)

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py makemigrations

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py migrate


Now start the server?
 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg4>python manage.py runserver

 Open google chrome and type the URL address like as following

http://127.0.0.1:8000/admin

Giver User Name : Heenukrish

Password : Krishnan@90  clikc Login


In above output the class ‘Employee’ will be added in admin page

And click “add” option you can add record into database
Prg5: To write a Program For Creating a New user In Admin Panel using
Django Package

Steps To create a New Project ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject Prg5

Steps To create a New App ?

 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py migrate

D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py startapp myapp5

Now the app will be created in the folder of Prg5

Steps To create a HTML File ?


 Open cmd-window and make a directory like as your wish
 Kindly note the directory should be created in Prg5-folder

D:\Python Tutorial\Python Programs\Python webapps\Prg5>md templates

Now the templates – directory will be created in the folder of Prg5

Create HTML file in Templates Folder ?


 Open Notepad App and type the following code

Index.html

<!DOCTYPE html>

<html>

<head>

<title> Authentication</title>

<body>

{% block content %} # we are going to use this html file into another file by using this code

<h1> Hello Index Page</h1>


{% endblock %}

</body>

</html>

Steps To create another HTML File ?


 Open cmd-window and make a directory like as your wish
 Kindly note the directory should be created in Prg5-folder

D:\Python Tutorial\Python Programs\Python webapps\Prg5>templates>md registration

Now the registration – directory will be created in the folder of templates

Create HTML file in Registration Folder ?


 Open Notepad App and type the following code

register.html

{% extends 'index.html' %}

{% block content %}

<h1> Create a new User</h1>

<form method="POST">

{% csrf_token %}

{{form.as_p}}

<button>Register</button>

</form>

{% endblock %}
Steps To create a new Own Duplicate Urls.py File in Prg ?

 Open Python IDE  file New


 D:\Python Tutorial\Python Programs\Python webapps\Prg5\myapp5

urls.py

from django.urls import path

from.import views

urlpatterns = [

path(' ',views.index,name=' index'),# Here by default the Home page will load

path('register/',views.register,name='register'),

Steps To create Original Urls.py File in Prg ?


 Open Python IDE  file Open
 D:\Python Tutorial\Python Programs\Python webapps\Prg5\myapp5

urls.py

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('',include("myapp5.urls"))

]
How to insert This HTML file into Django server ?

 Open Your myapp5 folder from Prg5


 D:\Python Tutorial\Python Programs\Python webapps\Prg5\myapp5>
 Open views.py – file and type the code like as following
 D:\Python Tutorial\Python Programs\Python webapps\Prg5\myapp5

Views.py

from django.shortcuts import render,redirect

from django.contrib.auth.forms import UserCreationForm

# Create your views here.

def index(request):

return render(request,'index.html')

def register(request):

if request.method=='POST':

form =UserCreationForm(request.POST)

if form.is_valid():

form.save()

return redirect('index')

else:

form=UserCreationForm()

return render(request,'registration/register.html',{'form':form})
Settings.py
 Under Application definition section we want to mention our Apps name like as
following

# Application definition

import os

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

' myapp5',

 Under Template section we want to mention our Template name like as following

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

DIRS': [os.path.join(BASE_DIR,'templates')],

'APP_DIRS': True,
'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

Now migrate the code ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py migrate

 we got the message Apply All migration


D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py
makemigrations

 we got the message No changes detected

Now Create Admin User name and Password ?


D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py
createsuperuser

Username(leave blank to use ‘Elcot’) : Krishjoshua

Passoword : Krishnan@90

Again Password : Krishnan@90

Superuser created successfully

Now start the server?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\Prg5>python manage.py runserver

 Open google chrome and type the URL address like as following

http://127.0.0.1:8000

http://127.0.0.1:8000/admin
http://127.0.0.1:8000/register
C-Create

R-Read

U-Update

D-Delete

1. Steps To create a New Database in MYSQL work Bench ?


 Open Mysql Work bench and create a new Data Base like as following
 Create database madhi;
 Now data base ready without any table and minimize the Mysql
2. Steps To create a New Project ?
 Open cmd and type the following code

C:\Users\ELCOT> pip install mysql

D:\Python Tutorial\Python Programs\Python webapps>django-admin startproject CRUD

3. Steps To create a New App ?


Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py startapp


operations

Now the app will be created in the folder of operations

4. Steps To Open a Folder Into Visual Studio Code IDE ?


 Open Visual Studio Code and Go to File Menu
 Click Open Folder  select your drive and folder like as following
 D:\Python Tutorial\Python Programs\Python webapps
 Click CRUD-folderClick Select Folder
 Now the Project ready to write code

5. Steps To Integrate your App and MYSQL to Django?


 Open settings.py – File and set the code like as following

settings.py
# Application definition

import os

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'operations',

DATABASES = {

'default': {

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

'NAME':'madhi',

'USER':'root',

'PASSWORD':'Krishnan@90',

'HOST':'localhost',

'PORT':'3306'

6. Steps To Create a New Model (Data Base Table)?


 Open Models.py – File from operations – Folder and set the code like as following

models.py
from django.db import models

class Employe(models.Model):

eid=models.CharField(max_length=20) # here 'eid' – column name

ename=models.CharField(max_length=50)

econtact=models.CharField(max_length=50)

def __str__(self):

return self.ename

class Meta: # we are going to map the above class name as table name

db_table="employ" # here the table name is 'employee'

7. Steps To Makemigrations and migrate Model ?


 Press Ctrl + ~ now terminal window will open (i.e) command prompt and the
command like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py makemigrations

Now we got the following messages :

Migrations for 'operations':

operations\migrations\0001_initial.py

- Create model Employe

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py migrate

Wait 2-Minutes and we got the following messages :

Operations to perform:

Apply all migrations: admin, auth, contenttypes, operations, sessions

Running migrations:

Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK

Applying admin.0001_initial... OK

Applying admin.0002_logentry_remove_auto_add... OK

Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK

Applying auth.0002_alter_permission_name_max_length... OK

Applying auth.0003_alter_user_email_max_length... OK

Applying auth.0004_alter_user_username_opts... OK

Applying auth.0005_alter_user_last_login_null... OK

Applying auth.0006_require_contenttypes_0002... OK

Applying auth.0007_alter_validators_add_error_messages... OK

Applying auth.0008_alter_user_username_max_length... OK

Applying auth.0009_alter_user_last_name_max_length... OK

Applying auth.0010_alter_group_name_max_length... OK

Applying auth.0011_update_proxy_permissions... OK

Applying auth.0012_alter_user_first_name_max_length... OK

Applying operations.0001_initial... OK

Applying sessions.0001_initial... OK

8. Steps To Create Admin ?


D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py createsuperuser

Username (leave blank to use 'elcot'): Heenukrish

Email address: [email protected]

Password:Krishnan@90

Password (again):Krishnan@90

Superuser created successfully.

9. Steps To Add Model(Data Base) To Admin Page ?


 Open admin.py – file from operations – Folder and type the following code

models.py
from django.contrib import admin

from operations.models import Employe

# Register your models here.

admin.site.register(Employe)

10.Steps To Start Server ?


 Open cmd – window and type like as following
D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver

11.Steps To Start Server ?


Open google chrome and type the URL address like as following

http://127.0.0.1:8000/admin

 After Login click on Employe from left hand side options and click on ADD EMPLOYE
from right hand side
 Fill all fields and click save and add another for insert more records
 After Insert all records open MYSQL and check there is record or not
12.Steps To Create UI of User ?
 Create a New Folder outside of CURD and operations folder
 Click new folder icon Folder name is: templates
 Open Settings.py under Template section we want to mention our Template name
like as following

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

DIRS': [os.path.join(BASE_DIR,'templates')],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

], }, },]

13.Create HTML file in Templates Folder ?


 Create 4-Html files like as following
 createrec.html
 readrec.html
 updaterec.html
 delete.html

createrec.html

<!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>Create Record in to Data Base</title>

</head>

<body>

<h1> Create records</h1>

</body>

updaterec.html

<!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>Update Record Into Data Base</title>

</head>

<body>

<h1>Update records </h1>

</body>

</html>

readrec.html

<!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>Read Record Into Data Base</title>

</head>

<body>

<h1>Read records </h1>

</body>

</html>

delete.html

<!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>Delete Record Into Data Base</title>

</head>

<body>

<h1>Delete records </h1>

</body>

</html>
14.How to insert These 4- HTML files into views.py ?
 Open views.py – file from operations – folder
 type the code like as following

views.py

from django.shortcuts import render

# Create your views here.

def createrecord(request):

return render(request,'createrec.html')

def updaterecord(request):

return render(request,'updaterec.html')

def readrecord(request):

return render(request,'readrec.html')

def deleterecord(request):

return render(request,'delete.html')

15.How to set Urls of These 4- HTML files into urls.py ?


 Open urls.py – file from CRUD – folder
 type the code like as following

urls.py

from django.contrib import admin

from django.urls import path

from operations.views import readrecord,createrecord,updaterecord,deleterecord

urlpatterns = [

path('admin/', admin.site.urls),

path('www.read.com',readrecord,name='read'),

path('www.create.com',createrecord,name='create'),

path('www.update.com',updaterecord,name='update'),

path('www.delete.com',deleterecord,name='delete'),]
16.Steps To Start Server ?
 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver

17.Steps To Start Server ?


Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.create.com

http://127.0.0.1:8000/www.update.com

http://127.0.0.1:8000/www.read.com

http://127.0.0.1:8000/www.delete.com

18.How to add forms.py for adding records in User Page ?


 Click Operations-Folder and click New File Options
 Filename : forms.py – file from operations – folder
 type the code like as following

forms.py

from django import forms

from operations.models import Employe # Importing data base here

class EmployeeForm(forms.ModelForm):

class Meta:

model=Employe # here include our model name

fields="__all__" # getting all fields from DB

19.Make changes in views.py ?


 Open views.py – file from operations – folder
 type the code like as following

views.py
from django.shortcuts import render

from operations.forms import EmployeeForm # here import above form.py

def createrecord(request):

form=EmployeeForm() # here user forms stored into form variable

context={

'form':form # here the form data send from form

return render(request,'createrec.html',context) # here the context send to


createrec.html file

20.How to add some designing component in- HTML files from bootstrap
website ?
 Open CMD and type the command like as following
 C:\Users\ELCOT>pip install django-crispy-forms
 After install we need to mention this crispy forms into settings.py

settings.py

# Application definition

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'operations',

'crispy_forms',

CRISPY_TEMPLATE_PACK="bootstrap4"

 Open Google chrome and type the following address in search bar
 Bootstrap
 Click first link  click Get Started button
 Click Getting started and click introduction option
 Under CSS –heading click COPY that code
 Paste in to createrec.html like as following

createrec.html

{% load crispy_forms_tags %}

<!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">

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
crossorigin="anonymous">

<title>Creating a New Record into DB</title>

</head>

<body>

<h1>Create A New Record in User Form</h1>

<div class="container">

<form method="POST">

{% csrf_token %}

{{form | crispy}}

<br>

<br>

<button class="btn btn-primary" type="submit"> Create</button>

</form>

</div>

</body>

</html>

21.Steps To Start Server ?


 Open cmd – window and type like as following
D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver
22.Steps To Start Server ?
Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.create.com

 Now form ready but didn’t work create option so kindly add some codes into
views.py

views.py

from django.shortcuts import render, redirect

from operations.forms import EmployeeForm # here import above form.py

# Create your views here.

def createrecord(request):

if request.method=="POST":

form=EmployeeForm(request.POST)

if form.is_valid():

form.save()

return redirect('read')

return redirect('create')

else:

form=EmployeeForm

context={
'form':form

return render(request,'createrec.html',context) # here the context send to createrec.html


file

23.Steps To Start Server ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver

24.Steps To Start Server ?


Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.create.com

 In above output the eid-767 will be added into DB

-------------------------------------------- Create Done!!!!!----------------------------------------------------

25.How to add some code For Reading Record ?


 Open views.py and add some following code

Views.py

from django.shortcuts import render,redirect

from operations.forms import EmployeeForm # here import above form.py

from operations.models import Employe

def readrecord(request):

obj=Employe.objects.all

return render(request,'readrec.html',{'data':obj})

26.add some code in readrec.html ?


 Open views.py and add some following code

readrec.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
crossorigin="anonymous">

<title>Reading Record From DB</title>

</head><body bgcolor="green" text="white">

<nav class="navbar navbar-expand-lg navbar-light bg-light shadow">

<div class="container-fluid">

<a class="navbar-brand" href="#">KRISH JOSHUA ISAC</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-


target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-
label="Toggle navigation">

<span class="navbar-toggler-icon"></span>
</button> <div class="collapse navbar-collapse" id="navbarNav">

<ul class="navbar-nav"> <li class="nav-item">

<a class="nav-link active" aria-current="page" href="www.create.com">Create</a>

</li> </ul></div> </div>

</nav><h2><center>Employee Details</center></h2>

<table class="table" border=5 bordercolor="white" width=50%>

<thead><tr> <th scope="col" bgcolor="blue">ID</th>

<th scope="col" bgcolor="red">E.ID</th>

<th scope="col" bgcolor="black">E.NAME</th>

<th scope="col" bgcolor="orange">E.CONTACT</th>

<th scope="col" bgcolor="purple">OPERAIONS</th>

</tr> </thead><tbody>

{% for e in data %}

<tr><th scope="row">{{e.id}}</th>

<td>{{e.eid}}</td>

<td>{{e.ename}}</td>

<td>{{e.econtact}}</td> <td>

<button class="btn btn-success"><a href="www.create.com">Create</a></button>

<button class="btn btn-success"><a href=" #">Update</a></button>

<button class="btn btn-danger"><a href=" #"> Delete</a></button>

</td> </tr> {% endfor %} </tbody></table> <br><br><br>

<marquee bgcolor="yellow"><font color="Comic Sans MS" size=5> Reading


Records!!!</marquee></body></html>

27.Steps To Start Server ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver

28.Steps To Start Server ?


Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.read.com

 Now we can view our records the above web page

-------------------------------------------------- Read Records Done !!!------------------------------------------

29.How to add some code For Updating Record ?


 Open updaterec.html and add some codes

Updaterec.html

{% load crispy_forms_tags %}

<!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">

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
crossorigin="anonymous">
<title>Updating Records</title>

</head><body>

<h1>Updating Record in User Form</h1>

<div class="container">

<form method="POST">

{% csrf_token %}

{{form | crispy}} <br><br>

<button class="btn btn-primary" type="submit">Update</button>

</form> </div></body></html>

30.How to add some code views.py ?


 Open views.py and add some codes

views.py

from django.shortcuts import render,redirect

from operations.forms import EmployeeForm # here import above form.py

from operations.models import Employe

from django.http import HttpResponse, response

def updaterecord(request,id):

obj=Employe.objects.get(id=id)

if request.method=="POST":

form=EmployeeForm(request.POST,instance=obj)

if form.is_valid():

form.save()

return redirect('read')

return redirect('update')

else:

form=EmployeeForm
context={

'form':form

return render(request,'updaterec.html',context)

31.How to add some code urls.py ?


 Open urls.py and add some codes

urls.py

from django.contrib import admin

from django.urls import path

from myapp2.views import sayHtml,createrecord,updaterecord,deleterecord

urlpatterns = [

path('admin/', admin.site.urls),

path('www.read.com',sayHtml,name='read'),

path('www.create.com',createrecord,name='create'),

path('www.update.com/<int:id>',updaterecord,name='update'),

path('www.delete.com',deleterecord,name='delete'),

32.How to add some code readrec.html ?

readrec.html

<button class="btn btn-success"><a ref="www.update.com/{{e.id}}">Update</a></button>

33.Steps To Start Server ?


 Open cmd – window and type like as following
D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver
34.Steps To Start Server ?
Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.read.com

click Update Button

 In above page the record eid=767 will be changed

------------------------------------------------- Update Done !!!------------------------------------------------

35.How to add some code For Delete Record ?


 Open readrec.html and add some codes

Readred.html

<button class="btn btn-danger"><a href="www.read.com/{{e.id}}"> Delete</a></button>

36. How to add some in urls.py ?


 Open readrec.html and add some codes

Urls.py
from django.contrib import admin

from django.urls import path

from operations.views import readrecord,createrecord,updaterecord,deleterecord

urlpatterns = [

path('admin/', admin.site.urls),

path('www.read.com',readrecord,name='read'),

path('www.create.com',createrecord,name='create'),

path('www.update.com/<int:id>',updaterecord,name='update'),

path('www.read.com/<int:id>',deleterecord,name='delete'),

37.How to add some in views.py ?


 Open readrec.html and add some codes

views.py

def deleterecord(request,id):

obj=Employe.objects.get(id=id)

obj.delete()

return redirect('read')

38.Steps To Start Server ?


 Open cmd – window and type like as following

D:\Python Tutorial\Python Programs\Python webapps\CRUD>python manage.py runserver

39.Steps To Start Server ?


Open google chrome and type the URL address like as following

http://127.0.0.1:8000/www.read.com
click Delete Button

 In above page the E-ID 767 will be deleted


1. Visit The Following Website?

 Bootstrap
 All releases
 V4.x  click 4.6
 Starter template

<!doctype html>

<html lang="en">

<head>

<!-- Required meta tags -->

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-
B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous">

<title>Hello, world!</title>

</head>

<body>

<h1>Hello, world!</h1>

<!-- Optional JavaScript; choose one of the two! -->


<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-


DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>

<!-- Option 2: Separate Popper and Bootstrap JS -->

<!--

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-


DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-
9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-
+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF"
crossorigin="anonymous"></script>

-->

</body>

</html>

2. Paste in Index.Html?
 Click copy that code
 And paste into index.html

3. Visit The Following Website?


 Again visit Bootstrap
 component
 navbar
 supported content
 Navbar  copy it and paste into

<body> section of index.html

<nav class="navbar navbar-expand-lg navbar-light bg-light">

<a class="navbar-brand" href="#">Navbar</a>

<button class="navbar-toggler" type="button" data-toggle="collapse" data-


target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav mr-auto">

<li class="nav-item active">

<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item dropdown">

<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"


data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

Dropdown

</a>

<div class="dropdown-menu" aria-labelledby="navbarDropdown">

<a class="dropdown-item" href="#">Action</a>

<a class="dropdown-item" href="#">Another action</a>


<div class="dropdown-divider"></div>

<a class="dropdown-item" href="#">Something else here</a>

</div>

</li>

<li class="nav-item">

<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>

</li>

</ul>

<form class="form-inline my-2 my-lg-0">

<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-


label="Search">

<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>

</form>

</div>

</nav>

Now the output will be like as following

4. Now we are going to make some changes in index.html like as following

<nav class="navbar navbar-expand-lg navbar-info bg-info">

<div class="container">

<a class="navbar-brand text-white" href="#">Navbar</a>

<a class="nav-link text-white" href="#">Home <span class="sr-


only">(current)</span></a>

</form>
</div></div> Here the container class will be end

5. To remove Below code from index.html

<li class="nav-item dropdown">


<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown"
role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-
disabled="true">Disabled</a>
</li>

<form class="form-inline my-2 my-lg-0">


<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
6. To add some code like as follwoiing

<nav class="navbar navbar-expand-lg navbar-info bg-info">

<div class="container">

<a class="navbar-brand text-white" href="#">Krish Joshua Isac</a>


<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav mr-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="#">Krish Joshua Isac <span class="sr-


only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

</ul>

</div>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav ml-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="#">Admin Profile <span class="sr-


only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link text-white" href="#">Logout</a>

</li>

</ul>

</div>

<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
7. To remove above code from index.html

Now the output will be like as following

8.To Take your new Font like As following


 Visit fontawesome.com
 And start for free
 And give email
 They will sent link to your registered email and click that confirmation link
 And set new password and give re-enter password now you got the login
page
 Click on your profile picture icon and click font Awesome CDN
 Click that copy icon blue colour icon and paste into index.html like as
following

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-
B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2
+l" crossorigin="anonymous">

<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.15.3/css/all.css"
integrity="sha384-
SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn
2fk" crossorigin="anonymous">

<title>Home!</title>

</head>
9. To add some code like as follwoiing

</nav>

<div class="containder">

<div class="row ml-4">

<div class="col-md-4">

<div class="card " >

<div class="cardheader bg-info text-white">

Information

</div>

<div class="card-body">

<marquee behavior="" direction="">

<h3 class="my-4">This is the Information

</h3>

</marquee>

</div>

</div>

</div>

<div class="col-md-8">

<div class="card " >

<div class="cardheader bg-info text-white">

Statistics

</div>

<div class="card-body">
<div class="row">

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="">

<div class="card my-card shadow text-center p-3">

<h4>Staff <i class="fas fa-users"></i></h4>

<h3>4</h3>

</div>

</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

<!-- End Top SIde -->

Now the output will be like as following

( Need to Connect Internet When Run this Web page )


10. To add some code in index.html like as follwoiing

<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-
SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk"
crossorigin="anonymous">

<link rel="stylesheet" href="./style.css">

<title>Home!</title>

</head>

<body>

11. To create a new style.css – File in Dashboard Folder:

Style.css and .my-card function

body{

background: rgb(230,227,227);

.my-card:hover{

transform: scale(1.1);

transition: 0.2s ease-in-out;

 In above code body – is a tag name for the background color as gray
 Hover – this class is used for zoom in,out style for card and
 Transition – is delay of card zoom in and out
 The above code about STAFF , do same think for other like as following
<div class="col-md-4">

<a class="text-decoration-none text-dark" href="">

<div class="card my-card shadow text-center p-3">

<h4>Staff <i class="fas fa-users"></i></h4> <h3>2</h3>

</div></a></div>

 Copy the above code from index.html and paste into same page for 2 –
Times
 and change the code like as following
<div class="col-md-4">

<a class="text-decoration-none text-dark" href="">

<div class="card my-card shadow text-center p-3">

<h4>Product <i class="fas fa-box"></i></h4> <h3>3</h3>

</div></a></div>

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="">

<div class="card my-card shadow text-center p-3">

<h4>Orders <i class="fas fa-shipping-fast"></i></h4> <h3>4</h3>

</div></a></div>
Now the output will be like as following

12. To create a new Chartjs CDN:


 Type the following code in index.html

</div>
</div>
</div>
</div>
</div>
</div>
<div class="containder">
<div class="row">
<div class="col md 6">
</div>
</div>
</div>

13. To Visit Following webpage:


 Visit charjs.org web page
 Click Get Started button
 Click Chart.js CDN option
 Click that first icon from right hand side and click Copy HTML option and paste into
index.html like as following
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css"
integrity="sha384-
SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk"
crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<link rel="stylesheet" href="./style.css">

<title>Home!</title>

</head> <body>

14. Visit again:


 And again Visit charjs.org web page
 Click Get Started button
 Under Creating a Chart title copy that code and paste into index.html

</div>
</div>
</div>
</div>
</div>
</div>
<div class="containder">
<div class="row">
<div class="col-md-6">
PASTE HERE
</div>
</div>
</div>

<div class="bg-white">

<canvas id="myChart1" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart1').getContext('2d');

var myChart1 = new Chart(ctx, {

type: 'pie',

data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],

datasets: [{

label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {
beginAtZero: true

});

</script>

</div>

</div>

<div class="col-md-6">

<div class="bg-white">

<canvas id="myChart" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

type: 'bar',

data: {

labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],

datasets: [{

label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',


'rgba(255, 159, 64, 1)'

],

borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {

beginAtZero: true

});

</script>

</div>

</div>

</div>

</div>
Now the output will be like as following

15. How to set Link on Staff ?


 open Index.html  press Ctrl + A and Press Ctrl + c ( copy all codes)
 make new file in current directory name is :Staff.html
 and paste there
 delete codes of 2-graphs (i.e) pie and bar

16. How to get Table on Staff ?


 Visit bootstrap
 Click Content Tab
 Click Tables
 Click 3rd Options (i.e … Table Head Option ( Fist,last, handle)
 Click Copy that code and paste into Staff.html

</div>

</div>

</div>

</div>

</div>

</div>

<div class="container">

<div class="row my-4">

<div class="col-md-4"></div>

<div class="col-md-8">

<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">First</th>

<th scope="col">Last</th>

<th scope="col">Handle</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Mark</td>

<td>Otto</td>

<td>@mdo</td>
</tr>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

</tr>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

</tr>

</tbody>

</table> </div></div> </div>

17. How to set link on word of Dashboard in Staff.html?

<a class="navbar-brand text-white" href="index.html">Krish Inventory System</a>

<a class="nav-link text-white" href="index.html">Dashboard <span class="sr-


only">(current)</span></a>

How to set link on word of Staff in index.html?

<a class="text-decoration-none text-dark" href="staff.html">

<div class="card my-card shadow text-center p-3">

<h4>Staff <i class="fas fa-users"></i></h4>

<h3>2</h3>

Now the output Of Staff


18. How to set Link on Products ?
 open staff.html  press Ctrl + A and Press Ctrl + c ( copy all codes)
 make new file in current directory name is :product.html
 and paste there
 and make some change in Tables code like as following

<div class="container">

<div class="row my-4">

<div class="col-md-4">

<div class="border bg-white p-3">

<h4>Add Product</h4>

<hr>

<form action="">

<input class="btn btn-success btn-block" type="submit" value="Add Product">

</form> </div> </div>

</div>

<div class="col-md-8">

19. Visit Boostrap ?


 Visit bootstrap
 In search box type forms
 Under overview title copy that link and paste into Product.html like as following

<form action=""> Paste Here

<input class="btn btn-success btn-block" type="submit" value="Add Product">

</form> </div> </div>

<form action="">

<div class="form-group">

<label for="exampleInputEmail1" class="form-label">Name</label>

<input type="email" class="form-control" id="exampleInputEmail1" aria-


describedby="emailHelp">

</div>

<div class="form-group">

<label for="exampleInputPassword1" class="form-label">Quantity</label>

<input type="password" class="form-control" id="exampleInputPassword1">

</div>

<div class="form-group">

<label for="inputState">Category</label>

<select id="inputState" class="form-control">

<option selected>Choose...</option>

<option>..........</option>

</select>

</div>

<input class="btn btn-success btn-block" type="submit" value="Add Product">

</form>

 Remove check Box code


20. Make Some Change in Table code in Product.Html
<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">Name</th>

<th scope="col">Category</th>

<th scope="col">Quantity</th>

<th scope="col">Activity</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row">1</th>

<td>Mark</td>

<td>Otto</td>

<td>@mdo</td>

<td><a class="btn btn-info btn-sm">Edit</a>

<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

<tr>

<th scope="row">2</th>

<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

<td><a class="btn btn-info btn-sm">Edit</a>


<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

<tr>

<th scope="row">3</th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

<td><a class="btn btn-info btn-sm">Edit</a>

<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

</tbody>

</table>

OUTPUT OF PRODUCT.HTML

21. How to set Link on Orders ?


 open product.html  press Ctrl + A and Press Ctrl + c ( copy all codes)
 make new file in current directory name is :order.html
 and paste there
 remove forms code and Button code (edit,delete)
 and make some change in Tables code like as following

<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">Product</th>

<th scope="col">Category</th>

<th scope="col">Quantity</th>

<th scope="col">Order By</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row">1</th>

<td>Mark</td>

<td>Otto</td>

<td>@mdo</td>

<td>

Krish

</td>

</tr>

<tr>

<th scope="row">2</th>
<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

<td>

Heenu

</td>

</tr>

<tr>

<th scope="row">3</th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

<td>

HeenuKrish

</td>

</tr>

</tbody>

</table>
OUTPUT OF ORDER.HTML

22. How to set Link on Profile Page ?


 open order.html  press Ctrl + A and Press Ctrl + c ( copy all codes)
 make new file in current directory name is :profile.html
 and paste there
 remove top side codes and Table code except container
 and make some change in Navbar code like as following

<a class="nav-link text-white" href="profile.html">Admin Profile <span class="sr-


only">(current)</span></a>

<div class="col-md-8">

<div class="card">

<div class="card-header bg-info text-white">

Profile Page

</div>

<div class="card-body">

<div class="row">

<div class="col-md-8">

<span class="h4">Profile Information</span><a class="btn btn-info btn-sm


float-right" href="">Edit</a>

<hr>
<table class="table bg-white table-borderless">

<tbody>

<tr>

<th scope="row">Name :</th>

<td>Krish</td>

</tr>

<tr>

<th scope="row">E-mail :</th>

<td>[email protected]</td>

</tr>

<tr>

<th scope="row">Phone :</th>

<td>+91 9994974215</td>

</tr>

<tr>

<th scope="row">Address:</th>

<td>130-A Block,Sri Ranga Nagar,Avinashi-641654.</td>

</tr>

</tbody>

</table>

</div>

<div class="col-md-4">

<img class="img-thumbnail" src="./media/profile-img1.jpeg" alt="">

</div>
</div>

</div>

</div>

</div>

</div>

</div>

OUTPUT OF PROFILE.HTML

1. Steps To Create A New Project?


 Open Visual studio code IDE and Press Ctrl + ~
 Now the Terminal window will be There and type the command like as following
D:\Python Tutorial\python inventory project>django-admin startproject inventoryproject

 Click File – Click Open Folder  select Your Project File ( ex : Inventoryproject)

2. Steps To Create A New App?


 Open Terminal window and type the command like as following

D:\Python Tutorial\python inventory project\inventoryproject>python manage.py startapp dashboard

3. To Add Your App into Setting.py ?


 Open setting.py From Inventory Folder and add some following codes

Setting.py

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'dashboard.apps.DashboardConfig',

4. Django Architecture
Krishinventory.com

Krishinventory.com
5. Take view.py from dashboard- Folder?

Views.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def index(request):

return HttpResponse('This is The Index Page')

def staff(request):

return HttpResponse('This is The Staff Page')

6. To Create a User Define Urls.py in dashboard-Folder ?


 Click on dashboard folder and Click New File Icon on Top
 Give name is : urls.py and type some following codes

Urls.py

from django.urls import path # Here we have import main url path from project folder

from .import views # Here we have import views.py files into user define Urls.py

urlpatterns=[

path('',views.index,name='index') # here we are accessing views file and index function

path('staff/',views.staff,name='staff')
]

7. Take urls.py file from inventoryproject- folder ?

Urls.py

from django.contrib import admin

from django.urls import path, include # here we have include user urls.py using include-
keyword

urlpatterns = [

path('admin/', admin.site.urls),

path('',include('dashboard.urls')) # here we have include all urls from the dashboard-


folder

8. Start The Server

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py runserver

9. Open Google Chrome and type the following address

127.0.0.1:8000
10. To make Templates-Folder outside of Both Folder(dashboard,inventoryproject):?
 Click on new folder-icon on the top
 And give name is : templates
 And take settings.py – file from inventoryproject Folder and add some codes like as
following

Settings.py

'DIRS': [BASE_DIR / 'templates']

 Click On Template – Folder and make new file


 Click new file icon-on the top and give name is : index.html
 Another one file name is : staff.html

Index.html

<!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>Home Page!</title>

</head>

<body>

<h3>This is the Templates Index Page</h3>

</body>

</html>
staff.html

<!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>Staff Page!</title>

</head>

<body>

<h3 style="color:blue">Staff Page</h3>

</body>

</html>

11. Make some changes in views.py – File

View.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def index(request):

return render(request,'index.html')

def staff(request):

return render(request,'staff.html')
12. Start The Server

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py runserver

13. Open Google Chrome and type the following address

127.0.0.1:8000/staff

14. To clear all codes on index.html and staff.html and save it as empty
15. To create a new folder inside of Template folder ?
 Click on Template- Folder and click New Folder icon
 Give name is : dashboard
 And move index.html and staff.html into dashboard folder
 Now both file successfully moved in dashboard- folder
 Then again click on Template – Folder and click New Folder Icon
 Give name is : partials
 Inside partials-Folder make 2-html files
 Base.html
 Nav.html
 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on index-file  open with notepad and copy code only from <nav>
 To </nav> and paste into nav.html – file

Nav.html

<!-- Nav Bar -->

<nav class="navbar navbar-expand-lg navbar-info bg-info">

<div class="container">

<a class="navbar-brand text-white" href="index.html">Krish Inventory System</a>


<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav mr-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="index.html">Dashboard <span class="sr-


only">(current)</span></a>

</li>

</ul>

</div>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav ml-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="profile.html">Admin Profile <span class="sr-


only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link text-white" href="#">Logout</a>

</li>

</ul>

</div>

</div>

</nav>
<!-- END Nav Bar -->

16. Visit Bootstrap


 Visit Bootstrap web page
 All releases
 V4.x  click 4.6
 Starter template
 Click copy and paste into base.html
 Make some change in <body> - tag like as following

Nav.html

<!doctype html>

<html lang="en">

<head>

<!-- Required meta tags -->

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-
B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous">

<title>Hello, world!</title>

</head>

<body>

{% include 'partials/nav.html' %}

<!-- Here we have include nav.html inside of base.html-->


<!-- Optional JavaScript; choose one of the two! -->

<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-


DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>

<!-- Option 2: Separate Popper and Bootstrap JS -->

<!--

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-


DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-
9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-
+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF"
crossorigin="anonymous"></script>

-->

</body>

</html>

17. Take index.html and type the following code

index.html

{% extends 'partials/base.html' %}

<!-- Here we have include base.html into index.html-->


18. Take staff.html and type the following code

staff.html

{% extends 'partials/base.html' %}

19. When run this file we got the Error!!! Template Not Found so we need to change
some codes into views.py

views.py

def index(request):

return render(request,'dashboard/index.html')

return render(request,'dashboard/staff.html')

20. Make internet connection before start the server


21. Start the server and open google chrome and type the following code

127.0.0.1.8000

127.0.0.1.8000/staff
22. Click on partials- Folder and make a new file the file name is : topnav.html
 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on index-file  open with notepad and copy code only from <div
class="containder">
 To </div> and paste into topnav.html – file

Topnav.html

<!-- Top Side-->

<div class="containder">

<div class="row ml-4">

<div class="col-md-4">

<div class="card " >

<div class="cardheader bg-info text-white">

Information

</div>

<div class="card-body">

<marquee behavior="" direction="">

<h3 class="my-4">This is the Information

</h3>

</marquee>

</div>

</div>

</div>

<div class="col-md-8">

<div class="card" >

<div class="cardheader bg-info text-white">

Statistics
</div>

<div class="card-body">

<div class="row">

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="staff.html">

<div class="card my-card shadow text-center p-3">

<h4>Staff <i class="fas fa-users"></i></h4>

<h3>2</h3>

</div>

</a>

</div>

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="product.html">

<div class="card my-card shadow text-center p-3">

<h4>Products <i class="fas fa-box"></i></h4>

<h3>3</h3>

</div>

</a>

</div>

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="order.html">

<div class="card my-card shadow text-center p-3">

<h4>Orders <i class="fas fa-shipping-fast"></i></h4>

<h3>4 </h3>
</div>

</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

<!-- End Top SIde -->

23. Take base.html and add some codes like as following in <body> section

<body>

{% include 'partials/nav.html' %}

{% include 'partials/topnav.html' %}

24. Now run the server and open google chrome type the following address

127.0.0.1:8000/staff
25. Take urls.py – file form dashboard-folder and make change

Urls.py

urlpatterns=[

path('',views.index,name='dashboard-index'),
path('staff/',views.staff,name='dashboard-staff'),

26. Take topnav.html and make some changes

Topnav.html

<div class="col-md-4">

<a class="text-decoration-none text-dark" href="{% url 'dashboard-staff' %}">

<div class="card my-card shadow text-center p-3">

<h4>Staff <i class="fas fa-users"></i></h4>

<h3>2</h3>

27. Take nav.html and make some changes

nav.html

<div class="container">

<a class="navbar-brand text-white" href="{% url 'dashboard-index' %}">Krish Inventory System</a>

<li class="nav-item active">

<a class="nav-link text-white" href="{% url 'dashboard-index' %}">Dashboard <span class="sr-


only">(current)</span></a>

28. Take base.html and make some changes in <title> section

<title > {% block title %} {% endblock %} </title>

29. Take staff.html and add some codes

{% extends 'partials/base.html' %}

{% block title %} Staff Page !{% endblock %}


30. Take index.html and some codes

{% extends 'partials/base.html' %}

{% block title %} Home Page !{% endblock %}

31. Take views.py and add some codes

Views.py

def product(request):

return render(request,'dashboard/product.html')

def order(request):

return render(request,'dashboard/order.html')

32. Take urls.py – file from dashboard-folder and add some codes

urlpatterns=[

path('',views.index,name='dashboard-index'), # here we are accessing views file and index


function

path('staff/',views.staff,name='dashboard-staff'),

path('product/',views.product,name='dashboard-product'),

path('order/',views.order,name='dashboard-order'),

33. To create a two-new html file inside of partials-folder


 Click on partials – folder
 Click new file icon on the top and give name is: product.html
 Another file name is : order.html

Product.html

{% extends 'partials/base.html' %}

{% block title %} Product Page !{% endblock %}

order.html

{% extends 'partials/base.html' %}
{% block title %} Order Page !{% endblock %}

34. Take topnav.html – files and add some codes

Topnav.html

<a class="text-decoration-none text-dark" href="{% url 'dashboard-product' %}">

<div class="card my-card shadow text-center p-3">

<h4>Products <i class="fas fa-box"></i></h4>

<h3>3</h3>

<a class="text-decoration-none text-dark" href="{% url 'dashboard-order' %}">

<div class="card my-card shadow text-center p-3">

<h4>Orders <i class="fas fa-shipping-fast"></i></h4>

35. Take base.html and add some codes

<body>

{% include 'partials/nav.html' %} <!-- Here we have include nav.html inside of


base.html-->

{% include 'partials/topnav.html' %}

{% block content%}

{% endblock %}

36. Take index.html and add some codes


 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on index-file  open with notepad and copy code only
 from
 To </div> and paste into index.html – file like as following

{% block content%}

<!-- PASTE HERE GRAPH CODE -->

<!-- Graph -->

<div class="containder">
<div class="row my-5">

<div class="col-md-6">

<div class="bg-white">

<canvas id="myChart1" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart1').getContext('2d');

var myChart1 = new Chart(ctx, {

type: 'pie',

data: {

labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],

datasets: [{

label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',


'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {

beginAtZero: true

});

</script>

</div>

</div>

<div class="col-md-6">

<div class="bg-white">

<canvas id="myChart" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

type: 'bar',

data: {

labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],


datasets: [{

label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {

beginAtZero: true
}

});

</script>

</div>

</div>

</div>

</div>

<!-- End Graph -->

{% endblock %}

37. Now the graph will not display there in index.html because we didn’t include
Chartjs.CDN
 Copy that Chartjs.CDN link from previous saved file (i.e : index-file)
Form

<!-- ChartJs CDN -->

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>

<!-- End Chartjs CDN -->

<!-- Custom CSS File-->

<link rel="stylesheet" href="./style.css">

<!-- End CSS File -->

 Paste Above the <title> section Of base.html


38. Make internet connection before start the server and type the following address

127.0.0.1:8000
39. To create a new static-Folder outside of Project and app folder?
 Click the mouse outside of dashboard and inventoryproject – folder
 And click new folder icon and give name is : static
 And click on folder static and click new file icon
 And give name is : style.css

Style.css

body{

background: rgb(230,227,227);

.my-card:hover{

transform: scale(1.1);

transition: 0.2s ease-in-out;

}
40. Take setting.py file of inventoryproject-folder and add some following code at the
end of statement

Settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS=[

BASE_DIR/"static/"

STATIC_ROOT =(BASE_DIR/"asert/")

 In above code ‘asert’ – folder will manage the CSS- files


 After adding the above code and open terminal window and type the following
command

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py collectstatic

 Now the assert-folder will be displayed automatically in current working projects


and also include some file

41. Take base.html and make some change

Base.html

{% load static %} ( add this code at 1st line of base.html )

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


42. Take staff.html and add some codes
 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on staff.html-file  open with notepad and copy code only
 from <table> To </table></div></div></div>
 and paste into staff.html – file like as following

staff.html

{% block content%}

<!-- PASTE HERE-->

<!-- Tables -->

<div class="container">

<div class="row my-4">

<div class="col-md-4"></div>

<div class="col-md-8">

<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">First</th>

<th scope="col">Last</th>

<th scope="col">Handle</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Mark</td>

<td>Otto</td>
<td>@mdo</td>

</tr>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

</tr>

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

<!-- End Tables -->

{% endblock %}
43. Take order.html and add some codes
 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on order.html-file  open with notepad and copy code only
 from <table> To </table></div></div></div>
 and paste into order.html – file like as following

order.html

{% block content%}

<!-- PASTE HERE-->

<!-- Tables -->

<div class="container">

<div class="row my-4">

<div class="col-md-4">

</div>

<div class="col-md-8">

<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">Product</th>

<th scope="col">Category</th>

<th scope="col">Quantity</th>

<th scope="col">Order By</th>

</tr>

</thead>

<tbody>

<tr>
<th scope="row">1</th>

<td>Mark</td>

<td>Otto</td>

<td>@mdo</td>

<td>

Krish

</td>

</tr>

<tr>

<th scope="row">2</th>

<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

<td>

Heenu

</td>

</tr>

<tr>

<th scope="row">3</th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

<td>

HeenuKrish

</td>

</tr>
</tbody>

</table>

</div>

</div>

</div>

<!-- End Tables -->

{% endblock %}

44. Take product.html and add some codes


 We have some code already for nav.html
 D:\Python Tutorial\python inventory project\Dashboard
 Right click on product.html-file  open with notepad and copy code only
 from <table> To </table></div></div></div>
 and paste into product.html – file like as following

product.html

{% block content%}

<!-- PASTE HERE-->

<!-- Tables -->

<div class="container">

<div class="row my-4">

<div class="col-md-4">

<div class="border bg-white p-3">

<h4>Add Product</h4>

<hr>

<form action="">

<div class="form-group">

<label for="exampleInputEmail1" class="form-label">Name</label>

<input type="email" class="form-control" id="exampleInputEmail1" aria-


describedby="emailHelp">
</div>

<div class="form-group">

<label for="exampleInputPassword1" class="form-label">Quantity</label>

<input type="password" class="form-control" id="exampleInputPassword1">

</div>

<div class="form-group">

<label for="inputState">Category</label>

<select id="inputState" class="form-control">

<option selected>Choose...</option>

<option>..........</option>

</select>

</div>

<input class="btn btn-success btn-block" type="submit" value="Add Product">

</form>

</div>

</div>

<div class="col-md-8">

<table class="table bg-white">

<thead class="bg-info">

<tr class="text-white">

<th scope="col">#</th>

<th scope="col">Name</th>

<th scope="col">Category</th>

<th scope="col">Quantity</th>

<th scope="col">Activity</th>

</tr>
</thead>

<tbody>

<tr>

<th scope="row">1</th>

<td>Mark</td>

<td>Otto</td>

<td>@mdo</td>

<td><a class="btn btn-info btn-sm">Edit</a>

<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

<tr>

<th scope="row">2</th>

<td>Jacob</td>

<td>Thornton</td>

<td>@fat</td>

<td><a class="btn btn-info btn-sm">Edit</a>

<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

<tr>

<th scope="row">3</th>

<td>Larry</td>

<td>the Bird</td>

<td>@twitter</td>

<td><a class="btn btn-info btn-sm">Edit</a>


<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

<!-- End Tables -->

{% endblock %}

45. To Create A New Model Using MySql


46. Steps To Integrate your App and MYSQL to Django?
 Open settings.py – File and set the code like as following

settings.py

import os

DATABASES = {

'default': {

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

'NAME':'inventory',

'USER':'root',

'PASSWORD':'Krishnan@90',

'HOST':'localhost',

'PORT':'3306'

47. Steps To Create a New Model (Data Base Table)?


 Open Models.py – File from dashboard – Folder and set the code like as following

models.py

from django.db import models

CATEGORY=(

('Stationary','Stationary'),

('Electronics','Electronics'),

('Food','Food'),

# Create your models here.

class Product(models.Model):

name=models.CharField(max_length=100,null=True)
category=models.CharField(max_length=20,choices=CATEGORY,null=True)

quantity=models.PositiveIntegerField(null=True)

def __str__(self):

return f'{self.name}-{self.quantity}'

48. Steps To Makemigrations and migrate Model ?


 Press Ctrl + ~ now terminal window will open (i.e) command prompt and the
command like as following

D:\Python Tutorial\python inventory project\inventoryproject>python manage.py makemigrations

Now we got the following messages :

Migrations for 'operations':

operations\migrations\0001_initial.py

- Create model Product

D:\Python Tutorial\python inventory project\inventoryproject>python manage.py migrate

Wait 2-Minutes

49. Create user name and password for Admin

D:\Python Tutorial\python inventory project\inventoryproject>python manage.py createsuperuser

Username (leave blank to use 'elcot'): Heenukrish

Email address: [email protected]

Password:Krishnan@90

Password (again):Krishnan@90

Superuser created successfully.

50. Start the server and open google and type the address like as following
127.0.0.1:8000/admin

 Give admin user name : Heenkrish


 Give admin password : Krishnan@90
 Click User and click ADD USER and add the user name and password like as following

User name : Heenu

Password : Krishnan@90

Re-enterpaswword : Krishnan@90  click save then it asking following fields

And also click save

Click Heenu  in Permission tab ....check the option only ( Active)

51. Take admin.py from dashboard-Folder and add some codes ?

from django.contrib import admin

from .models import Product # here we have import our database

# Register your models here.

admin.site.register(Product)

 Run the server again and load admin page


 There will be Dashboard added into our admin page (i.e) Database
 The click the on Product and click ADD PRODUCT

Name : Ball Pen Market

Category : Stationary

Quantity : 100  click Save

Name : Bag of Rice

Category : Food

Quantity : 200  click Save

Name : Hp Laptop

Category : Electronics

Quantity : 20  click Save


 The above 3-Products will be added into out database ( Database Name is:inventory)
 And Table name is ( dashboard_product)
 Open Your Mysql work bench and check the above details type the following queries
in mysql board like as following

use inventory;

select *from dashboard_product;

52. HOW CUSTOMIZE THE ADMINISTRATIVE PANEL


 Take admin.py from dashboard-folder

from django.contrib import admin

from .models import Product

from django.contrib.auth.models import Group

admin.site.unregister(Group) # here the group option will be remove in admin page

admin.site.site_header='KrishInventory Dashboard' # now the admin title will be changed

class ProductAdmin(admin.ModelAdmin): # Here view the products like as table in admin page

list_display=('name','category','quantity')

list_filter =['category']# we can filter the produt based on category by using filter

admin.site.register(Product,ProductAdmin)

 Run the server and open google chrome and type the following address
 127.0.0.1:8000/admin
 Logout from admin page ( click logout ) at top right corner
 Click log in again
 Now gave the username and password of User Account like as following

User Name : Heenu

Password : Krishnan@90  click Login

( Now we got error : Please enter the correct username and password for the staff account )

 Because we didn’t check the option staff account – In admin page under user
account)
 So login again in admin account and click on Users
 Click on Heenu and check the option staff status under permission
 Click save and now we can login user account
 Kindly note in user account there
 ( you don’t have permission to view or edit anything )
 Logout from user account
 And again login admin account and uncheck the option ( staff status) of users of
Heenu and click save
53. Creating a another model in model.py from dashboard folder ?
 Take model.py from dashboard-folder and add some following code

Model.py

from django.db import models

from django.db.models.deletion import CASCADE

from django.db.models.fields import DateField

from django.db.models.fields.related import ForeignKey

from django.contrib.auth.models import User

CATEGORY=(

('Stationary','Stationary'),

('Electronics','Electronics'),

('Food','Food'),

class Product(models.Model):

name=models.CharField(max_length=100,null=True)

category=models.CharField(max_length=20,choices=CATEGORY,null=True)

quantity=models.PositiveIntegerField(null=True)

class Meta:

verbose_name_plural='Product' # Here we have rename products as mention

def __str__(self):

return f'{self.name}-{self.quantity}'

class Order(models.Model):
product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True)

staff=models.ForeignKey(User,models.CASCADE,null=True)

order_quantity=models.PositiveIntegerField(null=True)

date=models.DateTimeField(auto_now_add=True)

class Meta:

verbose_name_plural='Order'

def __str__(self):

return f'{self.product} Ordered By {self.staff.username}'

54. To add above model into django by using makesmigrations?

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py makemigrations

Migrations for 'dashboard':

dashboard\migrations\0004_order.py

- Create model Order

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py migrate

Operations to perform:

Apply all migrations: admin, auth, contenttypes, dashboard, sessions

Running migrations:

Applying dashboard.0004_order... OK

55. Take admin.py and add a line like as following

from .models import Product,Order

admin.site.register(Product,ProductAdmin)

admin.site.register(Order)

 Now the Order- Model will be added into admin page in Dashboard panel

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py makemigrations

Migrations for 'dashboard':

dashboard\migrations\0005_auto_20210602_1553.py

- Change Meta options on order


- Change Meta options on product

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py migrate

Operations to perform:

Apply all migrations: admin, auth, contenttypes, dashboard, sessions

Running migrations:

Applying dashboard.0005_auto_20210602_1553... OK

56. How to make order in admin page ?


 Login to admin account and click on Order from dashboard panel
 Click ADD ORDER

Product staff Quantity

Hp Laptop Heenu 20  click save

Ball Pen Marker Heenukrish 12  click save

Bag of Rice Heenu 1  click save

57. To remove the following code from base.html from partial – folder ?

{% include 'partials/topnav.html' %} – remove this code form base.html

And paste this code into following files :

 Inside of {% block content %} – Of Index.html


 Inside of {% block content %} – Of product.html
 Inside of {% block content %} – Of order.html
 Inside of {% block content %} – Of staff.html

58. To add a new app into Inventoryproject like as following ?


 Press Ctrl+ ~ for terminal window and type the following command

D:\Python Tutorial\python inventory project\inventoryproject> python manage.py startapp user

59. To take setting.py from inventoryproject-folder and add app ?

INSTALLED_APPS = [

'django.contrib.admin',
'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'dashboard.apps.DashboardConfig',

'user.apps.UserConfig',

60. To create a New folder- Inside of template- folder ?


 Click on Template folder  click new folder at the top
 Give name is : user
61. To create 3- Html files – inside of user-folder?
 Click user-folder under template-folder
 Click new file icon and give name is : login.html
 Click new file icon and give name is : logout.html
 Click new file icon and give name is : register.html
 Take register.html and add some following code like as following

Register.html

{% extends 'p artials/base.html' %}

62. Take urls.py from inventoryproject-folder

urls.py

from django.contrib import admin

from django.urls import path, include

from user import views as user_view

urlpatterns = [

path('admin/', admin.site.urls),

path('',include('dashboard.urls')),

path('register/',user_view.register,name='register')

]
63. Take register.html and add some following codes

Register.html

{% extends 'partials/base.html' %}

{% block title %} Register Page! {% endblock %}

{% block content %}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3 ">

<div class="border bg-white p-3">

<h3>Registration Page!!!</h3>

<hr color="green">

<form method="POST">

{% csrf_token %}

{{ form }}

<input class="btn btn-success" type="submit" value="Register">

</form> </div> </div> </div> </div> {% endblock %}

64. Run the server and open google chrome and type the following address
127.0.0.1:8000/register

65. Take vi ews.py file from user-app- folder and add some code

Views.py

from django.shortcuts import render,redirect

from django.contrib.auth.forms import UserCreationForm

# Create your views here.

def register(request):

if request.method=='POST':

form=UserCreationForm(request.POST)

if form.is_valid():

form.save()

return redirect('dashboard-index')

else:

form=UserCreationForm()

context={

'form': form,
}

return render(request,'user/register.html',context)

66. Run the server and open google chrome and type the following address

127.0.0.1:800/register

 In above output the Krish- User will be added as new user


 Login admin page and click on users and there will be displayed the krish - user

67. To install crispy forms for more attractive of form


 Open terminal window and type the command like as following

D:\Python Tutorial\python inventory project\inventoryproject> Pip install django-crispy-forms


68. Take setting.py – file from inventoryproject-folder add a line like as following in
INSTALLED_APPS section

INSTALLED_APPS = [

'dashboard.apps.DashboardConfig',

'user.apps.UserConfig',

'crispy_forms',

CRISPY_TEMPLATE_PACK='bootstrap4'

69. Take register.html from user –folder and add some code like as following

Register.html

{% load crispy_forms_tags %}

{% block content %}

<form method="POST">

{% csrf_token %}

{{ form | crispy }}

<input class="btn btn-success" type="submit" value="Register">

</form>

70. Run the server and open google chrome and type the following address
127.0.0.1:8000/register

71. How to set Login – logout page


 Open urls.py –file from Inventoryproject –folder and add some codes like as
following

Urls.py

from django.contrib import admin

from django.urls import path, include

from user import views as user_view

from django.contrib.auth import views as auth_views # here we have import django


authentications

urlpatterns = [

path('admin/', admin.site.urls),
path('',include('dashboard.urls')),

path('register/',user_view.register,name='user-register'),

path('login/',auth_views.LoginView.as_view(template_name='user/login.html'),name='user-login'),

path('logout/',auth_views.LogoutView.as_view(template_name='user/login.html'),name='user-logout'),

72. Take login.html from user-folder inside of template folder

Login.html

{% extends 'partials/base.html' %}

{% block title %} Login Page! {% endblock %}

{% load crispy_forms_tags %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6">

<div class="border bg-white">

<h3>Login Page!!!</h3>

<hr color="green">

<form method="POST">

{% csrf_token %}

{{ form|crispy }}

<input class="btn btn-success" type="submit" value="Login">

</form>

</div>

</div>

</div>

</div>
{% endblock%}

73. Run the server and open google chrome and type the address like as following

127.0.0.1:8000/login

74. Take logout.html from user-folder inside of template –folder

Logout.html

{% extends 'partials/base.html' %}

{% block title %} Logout Page! {% endblock %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

<div class="border bg-white p-3">

<h3>Logout Page!!!</h3>
<hr color="red">

<div class="alert alert-danger">

<h4>You Have Logout </h4>

</div>

<a href="{% url 'user-login' %}"> Login </a>

</div> </div> </div> {% endblock%}

75. Run the server and open google chrome and type the address like as following

127.0.0.1:8000/logout

76. How to set link on login button inside of login.html ?


 Open settings.py –file from inventoryproject – folder and add the following code

Setting.html

STATIC_URL = '/static/'

STATICFILES_DIRS=[

BASE_DIR / "static/"

STATIC_ROOT =(BASE_DIR/"asert/")

LOGIN_REDIRECT_URL='dashboard-index'

# when user click login button it will show dashboard file


77. Run the server and open google chrome and visit login page

127.0.0.1:8000/login

Give User name : Heenukrish

Give password : Krishnan@90  click Login

( Now the dashboard page will be appear on the screen For unkown user )

78. How set link on logout on dashboard and how to add register and login link on
logout-page ?
 Open nav.html – file from partials –folder inside of template-folder

Nav.html

<!-- Nav Bar -->

<nav class="navbar navbar-expand-lg navbar-info bg-info">

{% if user.is_authenticated %} <!-- If u not include this line unknown user can access
your admin page-->

<!-- After gave above line in login page everything will disappear-->

<div class="container">

<a class="navbar-brand text-white" href="{% url 'dashboard-index' %}">Krish Inventory


System</a>

<button class="navbar-toggler" type="button" data-toggle="collapse" data-


target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav mr-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="{% url 'dashboard-index' %}">Dashboard <span


class="sr-only">(current)</span></a>

</li>
</ul>

</div>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav ml-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="profile.html">Admin Profile <span class="sr-


only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link text-white" href="{% url 'user-logout' %}">Logout</a>

</li>

</ul>

{% else %} <!-- Here if the user not availabe meand the 'register' and 'login' link will
appear on login page-->

<ul class="navbar-nav ml-auto">

<li class="nav-item active">

<a class="nav-link text-white" href="{% url 'user-register' %}">Register <span


class="sr-only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link text-white" href="{% url 'user-login' %}">Login</a>

</li>

</ul>

{% endif %}
</div>

</div>

</nav>

<!-- END Nav Bar -->

79. Run the server and open google chrome and type the following address

127.0.0.1:8000/login

Give User name : Heenukrish

Give password : Krishnan@90  click Login

( Now the dashboard page will be appear on the screen For authorised user )
80. Take urls.py – file from dashboard – folder and make some changes

path('dashboard/',views.index,name='dashboard-index')

81. Take urls.py – file from inventoryproject-folder and make some changes

path(' ',auth_views.LoginView.as_view(template_name='user/login.html'),name='user-login'),

82. Run the server and open google chrome and type the address

127.0.0.1:8000 ( Now here login-page act as home page )

83. After Run the above page and click register option

84. Now the register page will appear and fill following details

User Name : John

Password : Krishnan@90

Re-Enter Password : Krishnan@90  click Register

( Here problem is when the user click register then The home page don’t want to come ,
we need to redirect page to login-page )

85. Take viewa.py –File from user-app-folder and make some changes
Views.py

def register(request):

if request.method=='POST':

form=UserCreationForm(request.POST)

if form.is_valid():

form.save()

return redirect('user-login')

86. Now You can try to register a new user and after register the login –page will appear

87. if anyone try to type our address (127.0.0.1:8000/dashboard) , They can easily to
access our website without creating a new user

88. So, we can fix this problem by using Decorators

89. Take views.py – File from dashboard-Folder and add some codes

Views.py

from django.shortcuts import render

from django.http import HttpResponse

from django.contrib.auth.decorators import login_required

@login_required(login_url='user-login') # here @ denote decorator ...when user try to


visit our web they need to create login

def index(request):

return render(request,'dashboard/index.html')

@login_required(login_url='user-login')

def staff(request):

return render(request,'dashboard/staff.html')

@login_required(login_url='user-login')

def product(request):
return render(request,'dashboard/product.html')

@login_required(login_url='user-login')

def order(request):

return render(request,'dashboard/order.html')

90.Now if anyone try to type our address (127.0.0.1:8000/dashboard) , They can’t access
our website without login – page

91. Take views.py – File from dashboard-Folder and add some codes

Views.py

from django.shortcuts import render

from django.http import HttpResponse

from django.contrib.auth.decorators import login_required

@login_required

def index(request):

return render(request,'dashboard/index.html')

@login_required

def staff(request):

return render(request,'dashboard/staff.html')

@login_required

def product(request):

return render(request,'dashboard/product.html')

@login_required

def order(request):

return render(request,'dashboard/order.html')

92. Take settings.py – File from inventoryproject-Folder and add some codes

LOGIN_REDIRECT_URL='dashboard-index'

LOGIN_URL='user-login' # we can use this line for the step of 89


93.Now if anyone try to type our address (127.0.0.1:8000/dashboard) , They can’t access
our website without login – page

94.How to set if the admin means he can access everything and if the user means he can’t
access something we have mention in permission section

 Take index.html –file from dashboard inside of template folder

Index.html

{% extends 'partials/base.html' %}

{% block title %} Home Page! {% endblock %}

<!-- Here we have include base.html into index.html-->

{% block content%}

{% if user.is_authenticated and user.is_staff and user.is_superuser %}

<!—in above line if the user as admin the can access and also if the user have as staff and
superuser means they can also access -->

{% include 'partials/topnav.html' %}

<!-- Graph -->

<div class="containder">

<div class="row my-5">

<div class="col-md-6">

<div class="bg-white">

<canvas id="myChart1" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart1').getContext('2d');

var myChart1 = new Chart(ctx, {

type: 'pie',

data: {

labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],

datasets: [{
label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {

beginAtZero: true

}
}

});

</script>

</div>

</div>

<div class="col-md-6">

<div class="bg-white">

<canvas id="myChart" width="400 " height="200"></canvas>

<script>

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

type: 'bar',

data: {

labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],

datasets: [{

label: 'Products',

data: [12, 19, 3, 5, 2, 3],

backgroundColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],
borderColor: [

'rgba(255, 99, 132, 1)',

'rgba(54, 162, 235, 1)',

'rgba(255, 206, 86, 1)',

'rgba(75, 192, 192, 1)',

'rgba(153, 102, 255, 1)',

'rgba(255, 159, 64, 1)'

],

borderWidth: 1

}]

},

options: {

scales: {

y: {

beginAtZero: true

});

</script>

</div>

</div>

</div>

</div>

<!-- End Graph -->

{% else %} <!-- Here if the user has not a staff means they can access below file-->
{% include 'dashboard/staff_index.html '%}

{% endif %}

{% endblock %}

95. Run the server and open google chrome and type the following address

127.0.0.1:8000

User name : Heenukrish

Password : Krishnan@90  click Login ( now we are login as a admin , so we can


access everything )

User name : Krish

Password : Krishnan@90  click Login ( now we are login as a user , so we can


access specify page with some permissions) but we can’t access admin page

96. Create a new html into dashboard –folder inside of templates folder

 Click on dashboard-folder and click new file icon


 Type file name is : staff_index.html

Staff_index.html

<div class="container">

<div class="row mt-4">

<div class="col-md-4">

<div class="card">

<div class="card-header">

Make Request

</div>
<div class="card-body">

<form method="POST">

<input class="btn btn-info btn-block" type="submit" value="Make Request">

</form>

</div>

</div>

</div>

<div class="col-md-8">

<div class="card">

<div class="card-header">

Orders Records

</div>

<div class="card-body">

<table class="table bg-white">

<thead class="bg-info text-white">

<tr>

<th scope="col">Product</th>

<th scope="col">Category</th>

<th scope="col">Quantity</th>

</tr>

</thead>

<tbody>

<tr>

<td>Book</td>

<td>Stationary</td>

<td>10</td>
</tr>

<tr>

<td>Book</td>

<td>Stationary</td>

<td>10</td>

</tr>

<tr>

<td>Book</td>

<td>Stationary</td>

<td>10</td>

</tr>

<tr>

<td>Book</td>

<td>Stationary</td>

<td>10</td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

97. Run the server and open google chrome and type the following address

127.0.0.1:8000
User name : Krish

Password : Krishnan@90  click Login ( now we are login as a user , so we can


access specify page(staff_index.html) with some permissions) but we can’t access admin
page

98. how to set link on admin Profile ?

 Take views.py – file from user-app-folder and add some codes

Views.py

Add following method- at end

def profile(request):

return render(request,'user/profile.html')

99. Take urls.py – file from inventoryproject-folder add some codes

urlpatterns = [
path('admin/', admin.site.urls),

path('',include('dashboard.urls')), # here we have include all urls from the dashbaord-


folder

path('register/',user_view.register,name='user-register'),

path('',auth_views.LoginView.as_view(template_name='user/login.html'),name='user-
login'),

path('logout/',auth_views.LogoutView.as_view(template_name='user/logout.html'),name='
user-logout'),

path('profile/',user_view.profile,name='user-profile'),

100. Create a new html file

 Take user-folder inside of templates –folder


 Click new file icon and give name is :profile.html
 We have already profile .html in the location (D:\Python Tutorial\python inventory
project\Dashboard)
 So click profile.html  right click on it and open with notepad
 And copy from <table> to </div> - upto last 3 </div>
 And paste into profile.html of project location

Profile.html

{% extends 'partials/base.html' %}

{% block title %} Login Page! {% endblock %}

{% load crispy_forms_tags %}

{% block content%}

<!-- Tables -->

<div class="container">

<div class="row my-4">


<div class="col-md-4">

</div>

<div class="col-md-8">

<div class="card">

<div class="card-header bg-info text-white">

Profile Page

</div>

<div class="card-body">

<div class="row">

<div class="col-md-8">

<span class="h4">Profile Information</span><a class="btn btn-info btn-sm float-


right" href="">Edit</a>

<hr>

<table class="table bg-white table-borderless">

<tbody>

<tr>

<th scope="row">Name :</th>

<td>Krish</td>

</tr>

<tr>

<th scope="row">E-mail :</th>

<td>[email protected]</td>

</tr>
<tr>

<th scope="row">Phone :</th>

<td>+91 9994974215</td>

</tr>

<tr>

<th scope="row">Address:</th>

<td>130-A Block,Sri Ranga Nagar,Avinashi-641654.</td>

</tr>

</tbody>

</table>

</div>

<div class="col-md-4">

<img class="img-thumbnail" src="./media/profile-img1.jpeg" alt="">

</div>

</div>

</div>

</div>

{% endblock %}

101. take nav.html –file from partials-folder inside of templates- folder

Nav.html

<a class="nav-link text-white" href="{% url 'user-profile' %}">Admin Profile <span class="sr-
only">(current)</span></a>
102. Create a new model for admin profile

 Take models.py –file from user-app- folder

Models.py

from django.db import models

from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):

staff=models.OneToOneField(User,on_delete=models.CASCADE,null=True)

address=models.CharField(max_length=200,null=True)

phone=models.CharField(max_length=20,null=True)

image=models.ImageField(default='avatar.jpeg',upload_to='Profile_Images')

def __str__(self):

return f'{self.staff.username}-Profile'

103. D:\Python Tutorial\python inventory project\inventoryproject> python manage.py makemigrations

Migrations for 'user':

user\migrations\0001_initial.py

- Create model Profile

104. D:\Python Tutorial\python inventory project\inventoryproject> python manage.py migrate

Operations to perform:

Apply all migrations: admin, auth, contenttypes, dashboard, sessions, user

Running migrations:

Applying user.0001_initial... OK
105.Take admin.py – file from user-app-folder

Admin.py

from django.contrib import admin

from .models import Profile

# Register your models here.

admin.site.register(Profile)

106. Run the server and open google chrome and type the following address

127.0.0.1:800/ admin

( There the profile model – will be added into admin page )

 Click on profile – link and click ADD PROFILE

 After click save and again click on name Heenukrish , there will be currently:path
 When click on the currently path , got the error

107. Take settings.py –file from inventoryproject-folder

Settings.py

STATIC_ROOT =(BASE_DIR/"asert/")

MEDIA_ROOT=(BASE_DIR/ 'media')

MEDIA_URL='/media/'

LOGIN_REDIRECT_URL='dashboard-index'

LOGIN_URL='user-login'
108. Take urls.py –file from inventoryproject – folder

Urls.py

from os import stat

from django.contrib import admin

from django.urls import path, include

from django.views.generic.base import TemplateView # here we have include user urls.py


using include- keyword

from user import views as user_view

from django.contrib.auth import views as auth_views # here we have import django


authentications

from django.conf import settings

from django.conf.urls.static import static

urlpatterns = [

path('admin/', admin.site.urls),

path('',include('dashboard.urls')), # here we have include all urls from the dashbaord-


folder

path('register/',user_view.register,name='user-register'),

path('profile/',user_view.profile,name='user-profile'),

path('',auth_views.LoginView.as_view(template_name='user/login.html'),name='user-
login'),

path('logout/',auth_views.LogoutView.as_view(template_name='user/logout.html'),name
='user-logout'),

] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
 Now delete Heenukrish-profile details and also delete –Profile_Images-folder from
the project and again click ADD PROFILE option in admin page

 After click save and again click on name Heenukrish , there will be currently:path
 When click on the currently path , we can see the image where it will be saved
 Now in our project there media- Folder will be generated automatically and our
profile images save in there

109. How to set if admin login means their profile want to comes in admin profile

 Take profile.html – file from user-folder inside of templates-folder

Profile.html

<table class="table bg-white table-borderless">

<tbody>

<tr>

<th scope="row">Name :</th>

<td>{{ user.username }}</td>

</tr>
<tr>

<th scope="row">E-mail :</th>

<td>{{ user.email }}</td>

</tr>

<tr>

<th scope="row">Phone :</th>

<td>{{ user.profile.phone }}</td>

</tr>

<tr>

<th scope="row">Address:</th>

<td>{{ user.profile.address }}</td>

</tr>

</tbody>

</table>

</div>

<div class="col-md-4">

<img class="img-thumbnail" src="{{user.profile.image.url}}" alt="">

</div>

110. Run the server and open google chrome and type the following address

127.0.0.1:8000

User name : Heenukrish

Password: Krishnan@90  click Login

Click Admin Profile  now we can see the profile details of admin
111. Create signals.py –file in User-app- folder

 Click on folder User- and click new-file icon and give name is: signals.py

Signals.py

from django.contrib.auth.models import User

from .models import Profile

from django.db.models.signals import post_save

from django.dispatch import receiver

@receiver(post_save,sender=User)

def create_profile(sender,instance,created,**kwargs):

if created:

Profile.objects.create(staff=instance)

@receiver(post_save,sender=User)

def save_profile(sender,instance,**kwargs):

instance.profile.save()
112. take apps.py – file form user-app-folder and add some codes

Apps.py

from django.apps import AppConfig

class UserConfig(AppConfig):

default_auto_field = 'django.db.models.BigAutoField'

name = 'user'

def ready(self):

from user import signals

113. Run the server and open google chrome and type the following address

127.0.0.1:8000

Click register

User name : Joesph

Password : Krishnan@90

Re-enter password: Krishnan@90  click Register

Click login and type the username : Joesph and password : Krishnan@90  click Login

And click admin Profile ... there is only appear user name and default profile picture as
avatar.jpeg – picture

114. If you want to update , email, and address, Phone ....to visit the following address

127.0.0.1:8000/admin

User name : Heenukrish

Passsword: Krishnan@90  click Login

Click progile link and choose Joesph and update him details

Staff : Joesph
Address : 48, Kulli chettiar street, Near the Chennai silks , tirupur 641652

Phone : 9994477191

Image : if not choose any image meand it will take default image as avatar

Click save

115. Run the server and open google chrome and type the following address

127.0.0.1:8000

User name : Joesph

Password : Krishnan@90

Click login and click admin profile page ..... now there will be displayed ...e-mail, address,
phone of user

116. Take urls.py from inventoryproject-folder and some codes

urlpatterns = [

path('register/',user_view.register,name='user-register'),

path('profile/',user_view.profile,name='user-profile'),

path('profile/update',user_view.profile_update,name='user-profile-update'),

path('',auth_views.LoginView.as_view(template_name='user/login.html'),name='user-
login'),
path('logout/',auth_views.LogoutView.as_view(template_name='user/logout.html'),name
='user-logout')

] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

117. Take profile.html file from user-folder inside of templates-folder

Profile.html

<span class="h4">Profile Information</span><a class="btn btn-info btn-sm float-right"


href="{% url 'user-profile-update' %}">Edit</a>

118. create forms.py – file in user-app – folder and add some codes

Forms.py

from django import forms


from .models import Profile

from django.contrib.auth.models import User

from django.contrib.auth.forms import UserCreationForm

class UserUpdateForm(forms.ModelForm):

class Meta:

model=User

fields=['username','email']

class ProfileUpdateForm(forms.ModelForm):

class Meta:

model=Profile

fields=['address','phone','image']

119. How to set link on word Edit – In Admin Profile – Link ?

 Take views.py – file from User-app- Folder and add some codes

Views.py

from django.shortcuts import render,redirect

from django.contrib.auth.forms import UserCreationForm

from .forms import ProfileUpdateForm, UserUpdateForm

# Create your views here.

def register(request):

if request.method=='POST':

form=UserCreationForm(request.POST)

if form.is_valid():

form.save()

return redirect('user-login')

else:
form=UserCreationForm()

context={

'form': form,

return render(request,'user/register.html',context)# here we have include register.html from


template of user

def profile(request):

return render(request,'user/profile.html')

def profile_update(request):

if request.method=='POST':

user_form=UserUpdateForm(request.POST,instance=request.user)

profile_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile)

if user_form.is_valid() and profile_form.is_valid():

user_form.save()

profile_form.save()

return redirect('user-profile')

else:

user_form=UserUpdateForm(instance=request.user)

profile_form=ProfileUpdateForm(instance=request.user.profile)

context={

'user_form':user_form,

'profile_form':profile_form,

return render(request,'user/profile_update.html',context)

120. Create profile_update.html – file into user-folder inside of templates folder

Profile_update.html
{% extends 'partials/base.html' %}

{% block title %} Login Page! {% endblock %}

{% load crispy_forms_tags %}

{% block content%}

<div class="container">

<div class="row my-4">

<div class="col-md-4">

</div>

<div class="col-md-8">

<div class="card">

<div class="card-header bg-info text-white">

Profile Page

</div>

<div class="card-body">

<div class="row">

<div class="col-md-8">

<span class="h4">Profile Information</span>

<hr>

<form method="POST" enctype="multipart/form-data">

{% csrf_token %}

{{ user_form| crispy}}

{{ profile_form|crispy}}

<input class="btn btn-info " type="submit" value="Update">

</form>

</div>

</div>
</div>

</div>

{% endblock %}

121. Run the server and open google chrome and type the address

127.0.0.1:8000

User name: Heenu

Password : Krishnan@90

Click login ...............

Before Edit Profile

 click admin profile and click Edit Button .....


( now the update page will appear ) so you can change some fields like as following

Now you can login as new updating user Heenu as Madheena

User name : Madheena

Password: Krishnan@90  click login and Click Admin Profile


122. How to add product, delete, edit of product in Product – Panel of Dashboard- Page?
CRUD= Create , Read/Retrieve , Update , Delete

i. queryset = Product.objects.all() – it retrieving all fields from data base


ii. queryset = Product.objects.get() – it retrieving specific field from data base
iii. queryset = Product.objects.filter() – it is getting specific with fields group from
data base

123. How to Display the Products in Product – Page( Using Product.objects.all())

 Take views.py – file from Dashboard-Folder

Views.py

from .models import Product

@login_required(login_url='user-login')

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

context={

'items':items,

return render(request,'dashboard/product.html',context)

124. Take Product.html – file from templates- Folder add make some changes

Product.html

<tbody>

{% for item in items %}

<tr>

<th scope="row">{{ item.id }}</th>

<td>{{ item.name }}</td>

<td>{{ item.category }}</td>

<td>{{ item.quantity }}</td>


<td><a class="btn btn-info btn-sm">Edit</a>

<a class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

{% endfor %}

</tbody>

125. Run the server and open google chrome and type the following address

127.0.0.1:8000 ...... Login as admin and click on Prodcut Panel

( There the products will appear in the table like as following )

126. Create forms.py – file in dashboard- folder and type the following code

Forms.py

from django import forms

from django.db.models import fields

from .models import Product

class ProductForm(forms.ModelForm):

class Meta:

model=Product

fields=['name','category','quantity']
127. Take views.py – file form dashboard-folder and add some codes

Views.py

from django.shortcuts import render,redirect

from .forms import ProductForm

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

if request.method=="POST":

form=ProductForm(request.POST)

if form.is_valid():

form.save()

return redirect('dashboard-product')

else:

form=ProductForm()

context={

'items':items,

'form':form,

return render(request,'dashboard/product.html',context)

128. Take Product.html – file from templates- Folder add make some changes

Product.html

{% load crispy_forms_tags %}

{% block content%}

{% include 'partials/topnav.html' %}
<form method="POST">

{% csrf_token %}

{{ form | crispy }}

<input class="btn btn-success btn-block" type="submit" value="Add Product">

</form>

129. Run the server and open google chrome and type the address

127.0.0.1:8000  login as admin account  click Product Panel


130. Take views.py – file form dashboard-folder and add some codes

Views.py

def product_delete(request,pk): # pk is primary key

item=Product.objects.get(id=pk)

if request.method=="POST":

item.delete()

return redirect('dashboard-product')
return render(request,'dashbaord/product_delete.html')

131. Take urls.py – file from dashboard-folder

Urls.py

urlpatterns=[

path('product/',views.product,name='dashboard-product'),

path('product/delete/<int:pk>/',views.product_delete,name='dashboard-product-
delete'),

132. create product_delete.html – file into dashboard-folder inside of templates –folder

Product_delete.html

{% extends 'partials/base.html' %}

{% block title %} Delete Page !{% endblock %}

{% block content %}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

<div class="border bg-white p-3">

<h3>Delete Item</h3>

<hr color="green">

<div class="alert alert-danger">

<h4> Are You Sure You Wanto to Delete?</h4>

</div>

<form method="POST">

{% csrf_token %}

{{ form }}

<a class="btn btn-secondary" href="{% url 'dashboard-product' %}">Cancel</a>


<input class="btn btn-danger" type="submit" value="Confirm">

</form>

</div>

</div>

</div>

</div>

{% endblock %}

133. Take Product.html-file from dashboard-folder and add some codes

Product.html

<a class="btn btn-danger btn-sm" href="{% url 'dashboard-product-delete' item.id %}">Delete</a>

134. Run the server and open google chrome and type the address

127.0.0.1:8000 and login as admin and click product panel

Before delete of LG TV – Product


After delete of LG TV – Product

Click confirm the LG Tv will be deleted


135. Take urls.py – file form dashboard-folder and add some codes

Urls.py

urlpatterns=[

path('product/update/<int:pk>/',views.product_update,name='dashboard-product-
update'),
path('order/',views.order,name='dashboard-order'),

136. Take Product.html-file from dashboard-folder and add some codes

Product.html

<a class="btn btn-info btn-sm" href="{% url 'dashboard-product-update' item.id


%}">Edit</a>

<a class="btn btn-danger btn-sm" href="{% url 'dashboard-product-delete' item.id


%}">Delete</a>

137. Take views.py – file form dashboard-folder and add some codes

Views.py

def product_update(request,pk):

item=Product.objects.get(id=pk)

if request.method=="POST":

form=ProductForm(request.POST,instance=item) # here instance means to retrive


data from db and displayed it here

if form.is_valid():

form.save()

return redirect('dashboard-product')

else:

form=ProductForm(instance=item)

context={

'form':form,

return render(request,'dashboard/product_update.html',context)

138. Create Product_update.html in dashboard-folder inside of –templates

Product_update.html
{% extends 'partials/base.html' %}

{% block title %} Delete Page !{% endblock %}

{% load crispy_forms_tags %}

{% block content %}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

<div class="border bg-white p-3">

<h3>Edit Item</h3>

<hr color="green">

<form method="POST">

{% csrf_token %}

{{ form|crispy }}

<a class="btn btn-secondary" href="{% url 'dashboard-product' %}">Cancel</a>

<input class="btn btn-info" type="submit" value="Update">

</form>

</div>

</div>

</div>

</div>

{% endblock %}

139. Run the server and open google chrome and type the address

127.0.0.1:8000
Before Update Product is : Bag of Rice
After Update Product is : Bag of Rice

140. Take views.py – file form dashboard-folder and add some codes

Views.py

from django.contrib.auth.models import User

def staff(request):
workers=User.objects.all()

context={

'workers':workers

return render(request,'dashboard/staff.html',context)

141. Take Staff.html –file from dashboard-folder inside of templates-folder

Staff.html

<tbody>

{% for worker in workers %}

<tr>

<th scope="row"><a class="btn btn-info btn-sm" href="">View</a></th>

<td>{{ worker.username}}</td>

<td>{{ worker.email}}</td>

<td>{{ worker.profile.phone}}</td>

</tr>

{% endfor %}

</tbody>

</table>

142. Run the server open google chrome and type the address

127.0.0.1:8000 login as admin and type user name and password


Click staff panel ... there the no of user will be displayed in the table

143. Take urls.py – file form dashboard-folder and add some codes

Urls.py

urlpatterns=[

path('product/update/<int:pk>/',views.product_update,name='dashboard-product-
update'),

path('staff/details<int:pk>/',views.staff_details,name='dashboard-staff-details'),

path('order/',views.order,name='dashboard-order'),

144. Take staff.html-file from dashboard-folder and add some codes

staff.html

<th scope="row"><a class="btn btn-info btn-sm" href="{% url 'dashboard-staff-details'


worker.id %}">View</a></th>
145. Take views.py – file form dashboard-folder and add some codes

Views.py

@login_required(login_url='user-login')

def staff_details(request,pk):

workers=User.objects.get(id=pk)

context={

'workers':workers,

return render(request,'dashboard/staff_details.html',context)

146. create staff_details.html in dashboard-folder inside of templates – folder

Staff_details.html

{% extends 'partials/base.html' %}

{% block title %} Staff Page !{% endblock %}

{% block content%}

{% include 'partials/topnav.html' %}

<div class="container">

<div class="row my-4">

<div class="col-md-4">

</div>

<div class="col-md-8">

<div class="card">
<div class="card-header bg-info text-white">

Profile Page

</div>

<div class="card-body">

<div class="row">

<div class="col-md-8">

<span class="h4">Profile Information</span>

<hr>

<table class="table bg-white table-borderless">

<tbody>

<tr>

<th scope="row">Name :</th>

<td>{{ workers.username }}</td>

</tr>

<tr>

<th scope="row">E-mail :</th>

<td>{{ workers.email }}</td>

</tr>

<tr>

<th scope="row">Phone :</th>

<td>{{ workers.profile.phone }}</td>

</tr>

<tr>

<th scope="row">Address:</th>
<td>{{ user.profile.address }}</td>

</tr>

</tbody>

</table>

</div>

<div class="col-md-4">

<img class="img-thumbnail" src="{{workers.profile.image.url}}" alt="">

</div>

</div>

</div>

</div>

{% endblock %}

147. Run the server and open google chrome and type the address

127.0.0.1:8000

Login as admin and click on staff-Panel and click view button .....
148. Take views.py – file form dashboard-folder and add some codes

Views.py

from .models import Product,Order

@login_required(login_url='user-login')

def order(request):

orders=Order.objects.all()

context={

'orders':orders,

return render(request,'dashboard/order.html',context)

149. Take order.html-file from dashboard-folder and add some codes

order.html
<th scope="col">Order By</th>

<th scope="col">Date</th>

</tr>

</thead>

<tbody>

{% for orders in orders %}

<tr>

<td>{{orders.product}}</td>

<td>{{orders.product.category}}</td>

<td>{{orders.order_quantity}}</td>

<td>

{{ orders.staff.username}}

</td>

<td>

{{ orders.date}}

</td>

</tr>

{% endfor %}

</tbody>

150. Run the server and open google chrome and type the address
127.0.0.1:8000  login as admin  click Order panel
151. Take views.py from dashboard-folder

Views.py

@login_required(login_url='user-login') # here @ denote decorator ...when user try to


visit our web they need to create login

def index(request):

orders=Order.objects.all()

context={

'orders':orders,

return render(request,'dashboard/index.html',context)

152. Take staff_index.html and make some changes

Staff_index.html

{% for order in orders %}

{% if order.staff == user %}

<tr>

<td>{{order.product.name}}</td>

<td>{{order.product.category}}</td>

<td>{{order.order_quantity}}</td>

</tr>

{% endif %}

{% endfor %}

</tbody>

153. Run the server and open google chrome and type the address

127.0.0.1:8000

Login as User : (i.e ) – Madheena and give password .....


154. How to add some code for ( Make request ) in user login form

Take forms.py – file from dashboard-folder and add some codes

Forms.py

from .models import Product,Order

class OrderForm(forms.ModelForm):

class Meta:

model=Order

fields=['product','order_quantity']

155. Take views.py – file from dashboard –folder and add some codes

Views.py

from .forms import ProductForm,OrderForm

@login_required(login_url='user-login') # here @ denote decorator ...when user try to


visit our web they need to create login

def index(request):

orders=Order.objects.all()

if request.method=="POST":

form=OrderForm(request.POST)

if form.is_valid():

instance=form.save(commit=False)

instance.staff=request.user

instance.save()
return redirect('dashboard-index')

else:

form=OrderForm()

context={

'orders':orders,

'form':form,

return render(request,'dashboard/index.html',context)

156. Take staff_index.html and add some codes

Staff_index.html

{% load crispy_forms_tags %}

<div class="card-header">

Make Request

</div>

<div class="card-body">

<form method="POST">

{% csrf_token %}

{{form | crispy }}

<input class="btn btn-info btn-block" type="submit" value="Make Request">

</form>

157. Run the server and open google chrome and type the address

127.0.0.1:8000

Login as User : (i.e ) – Madheena and give password .....


Before make request

After make request

158. How to set Product has been added – message in Add product page

Views.py

from django.contrib import messages

@login_required(login_url='user-login')

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

if request.method=="POST":

form=ProductForm(request.POST)

if form.is_valid():

form.save()

product_name=form.cleaned_data.get('name')

messages.success(request,f'{product_name} has been added')

return redirect('dashboard-product')

else:

form=ProductForm()
context={

'items':items,

'form':form,

return render(request,'dashboard/product.html',context)

159. Open product.html – file

product.html

<div class="col-md-4">

{% for message in messages %}

{% if message %}

<div class="alert alert-{{ message.tags }}">

{{ message }}

</div>

{% endif %}

{% endfor %}

160.Run the server and open google chrome and type the address

127.0.0.1:8000 and login as admin and click product panel


161. How to set User has been added – message in Register page

 Take views.py-file from user-app-folder

Views.py

from django.contrib import messages

def register(request):

if request.method=='POST':

form=UserCreationForm(request.POST)

if form.is_valid():

form.save()

username=form.cleaned_data.get('username')

messages.success(request,f'Accoun has been created for {username}.Continue to Log in ')

return redirect('user-login')

162. Take login.html-file from user-template-folder


Login.html

<div class="col-md-6 offset-md-3">

{% for message in messages %}

{% if message %}

<div class="alert alert-{{ message.tags }}">

{{ message }}

</div>

{% endif %}

{% endfor %}

163. How show data on Chart on Admin page


 Take views.py – file from dashboard-folder

Views.py

def index(request):

orders=Order.objects.all()

products=Product.objects.all()

if request.method=="POST":

form=OrderForm(request.POST)

if form.is_valid():

instance=form.save(commit=False)

instance.staff=request.user

instance.save()

return redirect('dashboard-index')

else:

form=OrderForm()

context={

'orders':orders,

'form':form,

'products':products,

return render(request,'dashboard/index.html',context)

164. Take index.html – file from dashboard-template folder


Index.html

type: 'pie',

data: {

labels: [{% for order in orders %} '{{order.product.name}}', {% endfor %}],

datasets: [{

label: 'Orders',

data: [{% for order in orders %} {{ order.order_quantity }}, {% endfor %}],

type: 'bar',

data: {

labels: [{% for product in products %} '{{ product.name}}', {% endfor %}],

datasets: [{

label: 'Products',

data: [{% for product in products %} {{ product.quantity }}, {% endfor %}],

165. How to set no of count of product and staff and order in index – page
 Take views.py from dashboard-folder

Views.py

def staff(request):

workers=User.objects.all()

workers_count=workers.count()

context={

'workers':workers,

'workers_count':workers_count,

166. Take topnav.html

Topnav.html

<h4>Staff <i class="fas fa-users"></i></h4>

<h3>{{ workers_count}}</h3>

167. Take views.py from dashboard – folder

Views.py

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

workers_count=User.objects.all().count()

context={

'items':items,

'form':form,

'workers_count':workers_count,

def order(request):
orders=Order.objects.all()

workers_count=User.objects.all().count()

orders_count=orders.count()

context={

'orders':orders,

'workers_count':workers_count,

'orders_count':orders_count,

168. Take topnav.html

Topnav.html

<h4>Orders <i class="fas fa-shipping-fast"></i></h4>

<h3>{{ orders_count}} </h3>

169. Take views.py

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

workers_count=User.objects.all().count()

orders_count=Order.objects.all().count()

context={

'items':items,

'form':form,

'workers_count':workers_count,

'orders_count':orders_count,

def staff(request):
workers=User.objects.all()

workers_count=workers.count()

orders_count=Order.objects.all().count()

context={

'workers':workers,

'workers_count':workers_count,

'orders_count':orders_count,

def product(request):

items=Product.objects.all() # Using ORM - Method

#items=Product.objects.raw('SELECT * FROM dashboard_product') # we are using


genereally this code into MYSQL

workers_count=User.objects.all().count()

orders_count=Order.objects.all().count()

product_count=items.count()

context={

'items':items,

'form':form,

'workers_count':workers_count,

'orders_count':orders_count,

'product_count':product_count,

170. Take topnav.html


Topnav.html

<h4>Products <i class="fas fa-box"></i></h4>

<h3>{{ product_count}}</h3>

171. Take views.py

Views.py

def staff(request):

workers=User.objects.all()

workers_count=workers.count()

orders_count=Order.objects.all().count()

product_count=Product.objects.all().count()

context={

'workers':workers,

'workers_count':workers_count,

'orders_count':orders_count,

'product_count':product_count,

def order(request):

orders=Order.objects.all()

orders_count=orders.count()

workers_count=User.objects.all().count()

product_count=Product.objects.all().count()

context={

'orders':orders,

'workers_count':workers_count,

'orders_count':orders_count,
'product_count':product_count,

def index(request):

orders=Order.objects.all()

products=Product.objects.all()

orders_count=orders.count()

product_count=products.count()

workers_count=User.objects.all().count()

if request.method=="POST":

form=OrderForm(request.POST)

if form.is_valid():

instance=form.save(commit=False)

instance.staff=request.user

instance.save()

return redirect('dashboard-index')

else:

form=OrderForm()

context={

'orders':orders,

'form':form,

'products':products,

'orders_count':orders_count,

'product_count':product_count,

'workers_count':workers_count,

172. How to reset password for users


 Take urls.py –file from inventoryproject- folder

Urls.py

path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'),

path('password_reset_done/',auth_views.PasswordResetDoneView.as_view(),name='password_r
eset_done'),

path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_vi
ew(),name='password_reset_confirm'),

path('password_reset_complete/',auth_views.PasswordResetCompleteView.as_view(),name='pas
sword_reset_complete'),

173.Take login.html –file from user-templates

Login.html

<input class="btn btn-success" type="submit" value="Login">

<a class="mx-4" href="{% url 'password_reset' %}"> Forget Password?</a>

174. Take setting.py from Inventoryproject

Settings.py

LOGIN_REDIRECT_URL='dashboard-index'

LOGIN_URL='user-login'

EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST='smtp.gmail.com'

EMAIL_PORT=587

EMAIL_USE_TLS=True

EMAIL_HOST_USER='[email protected]'

EMAIL_HOST_PASSWORD='Krishnan@90'

( Before run the program click manage account of in your e-mail  click security tab 
and click Turn Off access under Less secure app access  turn on this option)

175. Run the server and open google chrome and type the address
127.0.0.1:8000  click Forget password

E-mail Address : [email protected]

Click Reset Password Button ( Now we got the following message )

Password reset sent

We’ve emailed you instructions for setting your password, if an account exists with the
email you entered. You should receive them shortly.

If you don’t receive an email, please make sure you’ve entered the address you registered
with, and check your spam folder.

( IN Above paragraph means we have send reset password link from


[email protected] to [email protected]

 The user want to login their e-mail and they need to click reset link after that
system asking

You're receiving this email because you requested a password reset for your user
account at 127.0.0.1:8000.

Please go to the following page and choose a new password:

http://127.0.0.1:8000/password_reset_confirm/Mg/ao6g99-
0e0e36686407a41115a1e42b189e7c24/

 Click above link the it asking to change password

New Password :

Confirm Password :

Click Change My Password Button

Password reset complete

Your password has been set. You may go ahead and log in now.

176. Take urls.py file from inventoryproject-folder


Urls.py

path('password_reset/',auth_views.PasswordResetView.as_view(template_name='user/p
assword_reset.html'),name='password_reset'),

path('password_reset_done/',auth_views.PasswordResetDoneView.as_view(template_na
me='user/password_reset_done.html'),name='password_reset_done'),

path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmVi
ew.as_view(template_name='user/password_reset_confirm.html'),name='password_rese
t_confirm'),

path('password_reset_complete/',auth_views.PasswordResetCompleteView.as_view(tem
plate_name='user/password_reset_complete.html'),name='password_reset_complete'),

177. Password_reset.html in user – template – folder

Password_reset.html

{% extends 'partials/base.html' %}

{% block title %} Password Reset Page! {% endblock %}

{% load crispy_forms_tags %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

{% for message in messages %}

{% if message %}

<div class="alert alert-{{ message.tags }}">

{{ message }}

</div>

{% endif %}

{% endfor %}

<div class="border p-3 bg-white">


<h3>Password Reset Page!!!</h3>

<hr color="green">

<form method="POST">

{% csrf_token %}

{{ form|crispy }}

<input class="btn btn-info" type="submit" value="Reset My Password">

</form>

</div>

</div>

</div>

</div>

{% endblock%}

178. Password_reset_done.html in user – template – folder

password_reset_done.html

{% extends 'partials/base.html' %}

{% block title %} Password Reset Done Page! {% endblock %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

<div class="border bg-white p-3">

<h3>Password Reset Done Page!!!</h3>

<hr color="red">

<div class="alert alert-info">

<h4>A mail has been sent to the email address you provided.

It has instruction you need to follow to reset your password </h4>


</div>

</div>

</div>

</div>

{% endblock%}

179. Password_reset_confirm.html in user – template – folder

Password_reset_confirm.html

{% extends 'partials/base.html' %}

{% block title %} Password Reset Confirm Page! {% endblock %}

{% load crispy_forms_tags %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

{% for message in messages %}

{% if message %}

<div class="alert alert-{{ message.tags }}">

{{ message }}

</div>

{% endif %}

{% endfor %}

<div class="border p-3 bg-white">

<h3>Password Reset Confirm Page!!!</h3>

<hr color="green">

<form method="POST">

{% csrf_token %}
{{ form|crispy }}

<input class="btn btn-info" type="submit" value="Confirm Password">

</form>

</div>

</div>

</div>

</div>

{% endblock%}

180. Password_reset_complete.html in user – template – folder

Password_reset_complete.html

{% extends 'partials/base.html' %}

{% block title %} Password Reset Complete Page! {% endblock %}

{% block content%}

<div class="container">

<div class="row mt-5">

<div class="col-md-6 offset-md-3">

<div class="border bg-white p-3">

<h3>Password Reset Complete Page!!!</h3>

<hr color="greeen">

<div class="alert alert-success">

<h4>Now! You can Log in your new password </h4>

</div>

<a href="{% url 'user-login' %}"> Login </a>

</div>

</div>

</div>
{% endblock%}

181. click Forget Password like as following

182. give user E-mail for changing password

183. we have sent instruction to user mail id like as following


184. The user want to click the reset link in their email like as following
185. After click the link the got the password change page like as following

186. Now the user got the confirm message

You might also like