Python Advance
Python Advance
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
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
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
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
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.
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 ):
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.
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
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.
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}
#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
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 (:).
OUTPUT:
Dictionary Values: {'Name': 'Krish', 'age': '31'}
Age is: 31
Name is: Krish
update Age is: 28
Python Function
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:
dip=lambda x:x*10
print(dip(5)) # single argument
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.
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)
# 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.
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.
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())
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
OUTPUT:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'division', 'multiplication', 'summation']
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.
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)
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 .
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 .
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.
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
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
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
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.
Function A count=count+1
Function A time.sleep(3)
Function A print(msg)
Function B count=0
times . try:
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
OUTPUT:
OUTPUT:
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:
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:
root=Tk()
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:
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.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:
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:
root=Tk()
root.geometry("700x500")
#photo=PhotoImage(file="c:\\User\\vijay\download\\new_age.png")
#myimage=Label(image=photo)
#myimage.grid(row=0,column=1)
def calculateage():
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="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)
c.create_window(100,100,window=l2)
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
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
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
OUTPUT:
Your file will be saved in Your current working directory .. Your file name will be as
following
root=Tk()
def cal_func():
def calval():
# in above statement year will be shown 2021 and 5th month and day is 14
cal.pack(fill="both", expand=True)
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:
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()
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')
k.show()
OUTPUT-1:
Make change in Code
exp=[0,0,0,0,0.5]
k.pie(voot,labels=member,autopct='%.f',startangle=90,explode=exp)
OUTPUT-2:
Prg117: To write a Program Merge Two Video files Using moviepy Package:
from moviepy.editor import*
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')
OUTPUT:
Go and check your current directory file ... there the video file will be converted as audio file
the file name is : song1.mp3
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)
k.svg('YoutubeQr.svg',scale=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.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("1: Shutdown")
print("2: Restart")
print("3: Exit")
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
Step-1 :
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")
# 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
# if you wan to check your data base connceted or not you can use following code
'''--------------------------------------------------------------------
if con:
print("connceted successfully")
else:
-----------------------------------------------------------------------'''
def insert(name,age,city):
res=con.cursor()
res.execute(sql,user) # here the execute() method to assign the value of exact field
def update(name,age,city,id):
res=con.cursor()
user=(name,age,city,id)
res.execute(sql,user)
con.commit()
def select():
res.execute(sql)
#result=res.fetchone() # it is used to retrive the top most record of the DB (i.e) First
record
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"]))
def delete(id):
res=con.cursor()
user=(id,)
res.execute(sql,user)
con.commit()
while True: # here we are displaying continues output using while True
print("5: Exit")
if choice==1:
name=input("Enter Name:")
age=input("Enter Age:")
city=input("Enter City:")
elif choice==2:
name=input("Enter Name:")
age=input("Enter Age:")
city=input("Enter City:")
elif choice==3:
elif choice==4:
id=input("Enter ID to Delete:")
delete(id) # calling Delete() - Method
elif choice==5:
else:
'''-------------------------------- End-----------------------''''
con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")
value=[(7,'Jeni',6,'Avinashi'),(8,'Bharath',10,'annur'),(9,'Leesya',12,'sivakashi')]
cur=con.cursor()
a=cur.executemany(sql,value)
print("Success")
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="Krishnan@90",data
base="hk")
cur=con.cursor()
for r in result:
print(r)
cur.execute(sh)
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*
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
vals=(user,passw) # here usname and password stored as tuple in to the variable 'vals'
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
# in above code 'data' variable will receive the value from connection() - method
else:
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)
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.pack()
root.mainloop()
OUTPUT-1: Exact User Login
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
--------------------------------------------------------------- ---------------------------------------------------
OUTPUT
#2] if you want to change shape you can use following method
krish.shape("turtle")
OUTPUT
help(turtle.shape)
#4] if you want to change and want to know about shape color
# 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()
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()
OUTPUT:
krish.circle(100,180) # It makes semi circle(or) Arc
import turtle
krish=turtle.Turtle()
#help(turtle.bgcolor)
'''--------------------Fill Circle----------------'''
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
krish.begin_fill()
krish.fillcolor("red")
krish.circle(100,steps=3)
krish.end_fill() # if not mention this you did not get fill also
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:
import turtle
t=turtle.Turtle()
t.circle(100)
t.up()
t.down()
t.circle(50)
OUTPUT:
import turtle
t=turtle.Turtle()
t.up()
t.goto(0,-50)
t.down()
t.begin_fill()
t.fillcolor("green")
t.circle(50)
t.end_fill()
t.up()
t.goto(150,150)
t.down()
t.begin_fill()
t.fillcolor("orange")
t.circle(50)
t.end_fill()
t.up()
t.goto(-150,150)
t.down()
t.begin_fill()
t.fillcolor("blue")
t.circle(50)
t.end_fill()
t.up()
t.down()
t.begin_fill()
t.fillcolor("red")
t.end_fill()
t.up()
t.goto(150,-150)
t.down()
t.begin_fill()
t.fillcolor("yellow")
t.circle(-50)
t.end_fill()
t.up()
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:
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:
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.pensize(i/10+1)
t.forward(i)
t.left(59)
OUTPUT:
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:
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')
moon=turtle.Turtle()
moon.hideturtle()
star=turtle.Turtle()
star.speed(0)
star.hideturtle()
colors=['red','blue','orange','yellow','magenta','purple','peru','ivory','dark orange']
text=turtle.Turtle()
text.speed(6)
text.hideturtle()
def draw_moon(pos,color):
x,y=pos
moon.color(color)
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')
return (random.randint(-390,390),random.randint(-200,290))
def random_length():
return random.randint(5,25)
draw_moon((-300,170),'white')
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
import socket
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
print("waiting")
print(" Got Connection From :",addr) # here we are printing the connection address
# 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
import socket
s=socket.socket()
host=socket.gethostname()
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:
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
import time,socket,sys
print("Intialising.......")
time.sleep(1)
s.bind((host,port))
print(s_name," has connected to chat room") # here we are printing client name
while True:
message=input(str("Me:"))
print(s_name,":",message)
import time,socket,sys
print("Intialising.......")
time.sleep(1)
s=socket.socket()
shost=socket.gethostname()
ip=socket.gethostbyname(shost)
print(shost,"(",ip,")\n")
port=1234
time.sleep(1)
s.connect((host,port))
print("\n connected")
print(s_name," has connected to chat room") # here we are printing server name
while True:
print(s_name,":",message)
message=input(str("Me:"))
OUTPUT:
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
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):
elif(e2.index("end")==0):
elif(e3.index("end")==0):
else:
else:
g=rvar.get()
course=cvar.get()
db=dob.get_date()
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.place(x=70,y=50)
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.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)
dob=DateEntry(root,width=27,background='brown',forground='white',date_pattern='dd/m
m/Y',borderwidth=3)
dob.place(x=240,y=230)
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)
cvar=StringVar()
cvar.set("Select Course")
option=("Python","Java","C","CPP")
o=OptionMenu(root,cvar,*option)
o.place(x=240,y=365,width=190)
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
import mysql.connector
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")
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()
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()
res.execute(sql,user) # here the execute() method to assign the value of exact field
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()
user=(r,)
res.execute(sql,user)
con.commit()
e1.delete(0,'end')
def update():
res=con.cursor()
r=e1.get()
n=e2.get()
s=e3.get()
user=(n,s,r)
res.execute(sql,user)
con.commit()
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')
res.execute(sql)
rows=res.fetchall()
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.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.place(x=80,y=180)
e4=Entry(textvariable=t)
e4.place(x=280,y=180)
eng.place(x=80,y=230)
e5=Entry(textvariable=e)
e5.place(x=280,y=230)
mat.place(x=80,y=280)
e6=Entry(textvariable=m)
e6.place(x=280,y=280)
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-(Delete Record )
OUTPUT-(Delete Record In MYSQL )
OUTPUT-(Search Record )
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
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
(in above code ( Prg1) – Folder will be created in current running directory )
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?
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
Password (again) :
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
Views.py
from django.shortcuts import render
def sayHello(request):
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',
urls.py
Under url patterns section we want to mention our url name like as following
from django.contrib import admin
from myapp1.views import sayHello # here we have import 'sayHello' - method from
views.py in myapp1-apps folder
urlpatterns = [
path('admin/', admin.site.urls),
Open google chrome and type the URL address like as following
http://127.0.0.1:8000/www.krishjoshuaisac.com
OUTPUT:
Hello.html
<html>
<title>Heenu Krish</title>
<font face="Arial"></center>
</center>
</font>
</body>
</html>
Views.py
from django.shortcuts import render
def sayHtml(request):
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 myapp2.views import sayHtml # here we have import 'sayHtml' - method from
views.py in myapp2-apps folder
urlpatterns = [
path('admin/', admin.site.urls),
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 ?
Views.py
def sayHtml(request):
return render(request,'Hello.html',{'name':s})
Hello.html
<font face="Arial"></center>
</center>
</font>
</body>
</html>
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
Home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body bgcolor="red">
</font></center>
<font color="cyan">
<h2>
<UL>
</UL>
<marquee bgcolor="white">
<font color="green">
</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>
</font><form name="fm1">
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</center>
<br><br><br>
<marquee bgcolor="pink">
</marquee>
</body>
</html>
How to insert This HTML file into Django server ?
Views.py
from django.shortcuts import render
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
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
urlpatterns = [
path('www.login.com',login,name='login'),
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)
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'
models.py
class Employee(models.Model):
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
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 ‘
admin.py
admin.site.register(Employee)
Open google chrome and type the URL address like as following
http://127.0.0.1:8000/admin
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
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
</body>
</html>
register.html
{% extends 'index.html' %}
{% block content %}
<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 ?
urls.py
from.import views
urlpatterns = [
path(' ',views.index,name=' index'),# Here by default the Home page will load
path('register/',views.register,name='register'),
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include("myapp5.urls"))
]
How to insert This HTML file into Django server ?
Views.py
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',
],
},
},
Passoword : Krishnan@90
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
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'
models.py
from django.db import models
class Employe(models.Model):
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
operations\migrations\0001_initial.py
Operations to perform:
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
Password:Krishnan@90
Password (again):Krishnan@90
models.py
from django.contrib import admin
admin.site.register(Employe)
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',
], }, },]
createrec.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
updaterec.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
readrec.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</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
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')
urls.py
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
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
forms.py
class EmployeeForm(forms.ModelForm):
class Meta:
views.py
from django.shortcuts import render
def createrecord(request):
context={
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">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<form method="POST">
{% csrf_token %}
{{form | crispy}}
<br>
<br>
</form>
</div>
</body>
</html>
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
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
http://127.0.0.1:8000/www.create.com
Views.py
def readrecord(request):
obj=Employe.objects.all
return render(request,'readrec.html',{'data':obj})
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">
<div class="container-fluid">
<span class="navbar-toggler-icon"></span>
</button> <div class="collapse navbar-collapse" id="navbarNav">
</nav><h2><center>Employee Details</center></h2>
</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>
http://127.0.0.1:8000/www.read.com
Updaterec.html
{% load crispy_forms_tags %}
<!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>Updating Records</title>
</head><body>
<div class="container">
<form method="POST">
{% csrf_token %}
</form> </div></body></html>
views.py
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)
urls.py
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'),
readrec.html
http://127.0.0.1:8000/www.read.com
Readred.html
Urls.py
from django.contrib import admin
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'),
views.py
def deleterecord(request,id):
obj=Employe.objects.get(id=id)
obj.delete()
return redirect('read')
http://127.0.0.1:8000/www.read.com
click Delete Button
Bootstrap
All releases
V4.x click 4.6
Starter template
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<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>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
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
<span class="navbar-toggler-icon"></span>
</button>
</li>
<li class="nav-item">
</li>
Dropdown
</a>
</div>
</li>
<li class="nav-item">
</li>
</ul>
</form>
</div>
</nav>
<div class="container">
</form>
</div></div> Here the container class will be end
<div class="container">
<span class="navbar-toggler-icon"></span>
</button>
</li>
<li class="nav-item">
</li>
</ul>
</div>
</li>
<li class="nav-item">
</li>
</ul>
</div>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
7. To remove above code from index.html
<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="col-md-4">
Information
</div>
<div class="card-body">
</h3>
</marquee>
</div>
</div>
</div>
<div class="col-md-8">
Statistics
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<h3>4</h3>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-
SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk"
crossorigin="anonymous">
<title>Home!</title>
</head>
<body>
body{
background: rgb(230,227,227);
.my-card:hover{
transform: scale(1.1);
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">
</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">
</div></a></div>
<div class="col-md-4">
</div></a></div>
Now the output will be like as following
</div>
</div>
</div>
</div>
</div>
</div>
<div class="containder">
<div class="row">
<div class="col md 6">
</div>
</div>
</div>
<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>
</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">
<script>
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
});
</script>
</div>
</div>
<div class="col-md-6">
<div class="bg-white">
<script>
type: 'bar',
data: {
datasets: [{
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
});
</script>
</div>
</div>
</div>
</div>
Now the output will be like as following
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="col-md-4"></div>
<div class="col-md-8">
<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>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
<h3>2</h3>
<div class="container">
<div class="col-md-4">
<h4>Add Product</h4>
<hr>
<form action="">
</div>
<div class="col-md-8">
<form action="">
<div class="form-group">
</div>
<div class="form-group">
</div>
<div class="form-group">
<label for="inputState">Category</label>
<option selected>Choose...</option>
<option>..........</option>
</select>
</div>
</form>
<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>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</td>
</tr>
</tbody>
</table>
OUTPUT OF PRODUCT.HTML
<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>
</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
<div class="col-md-8">
<div class="card">
Profile Page
</div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<hr>
<table class="table bg-white table-borderless">
<tbody>
<tr>
<td>Krish</td>
</tr>
<tr>
<td>[email protected]</td>
</tr>
<tr>
<td>+91 9994974215</td>
</tr>
<tr>
<th scope="row">Address:</th>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
OUTPUT OF PROFILE.HTML
Click File – Click Open Folder select Your Project File ( ex : Inventoryproject)
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
def index(request):
def staff(request):
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('staff/',views.staff,name='staff')
]
Urls.py
from django.urls import path, include # here we have include user urls.py using include-
keyword
urlpatterns = [
path('admin/', admin.site.urls),
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
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page!</title>
</head>
<body>
</body>
</html>
staff.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Staff Page!</title>
</head>
<body>
</body>
</html>
View.py
def index(request):
return render(request,'index.html')
def staff(request):
return render(request,'staff.html')
12. Start The Server
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
<div class="container">
<span class="navbar-toggler-icon"></span>
</button>
</li>
</ul>
</div>
</li>
<li class="nav-item">
</li>
</ul>
</div>
</div>
</nav>
<!-- END Nav Bar -->
Nav.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<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' %}
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
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>
index.html
{% extends 'partials/base.html' %}
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')
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
<div class="containder">
<div class="col-md-4">
Information
</div>
<div class="card-body">
</h3>
</marquee>
</div>
</div>
</div>
<div class="col-md-8">
Statistics
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<h3>2</h3>
</div>
</a>
</div>
<div class="col-md-4">
<h3>3</h3>
</div>
</a>
</div>
<div class="col-md-4">
<h3>4 </h3>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
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'),
Topnav.html
<div class="col-md-4">
<h3>2</h3>
nav.html
<div class="container">
{% extends 'partials/base.html' %}
{% extends 'partials/base.html' %}
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('staff/',views.staff,name='dashboard-staff'),
path('product/',views.product,name='dashboard-product'),
path('order/',views.order,name='dashboard-order'),
Product.html
{% extends 'partials/base.html' %}
order.html
{% extends 'partials/base.html' %}
{% block title %} Order Page !{% endblock %}
Topnav.html
<h3>3</h3>
<body>
{% include 'partials/topnav.html' %}
{% block content%}
{% endblock %}
{% block content%}
<div class="containder">
<div class="row my-5">
<div class="col-md-6">
<div class="bg-white">
<script>
type: 'pie',
data: {
datasets: [{
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
});
</script>
</div>
</div>
<div class="col-md-6">
<div class="bg-white">
<script>
type: 'bar',
data: {
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
});
</script>
</div>
</div>
</div>
</div>
{% 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
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
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);
}
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/")
Base.html
staff.html
{% block content%}
<div class="container">
<div class="col-md-4"></div>
<div class="col-md-8">
<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>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
{% 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%}
<div class="container">
<div class="col-md-4">
</div>
<div class="col-md-8">
<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>
</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>
{% endblock %}
product.html
{% block content%}
<div class="container">
<div class="col-md-4">
<h4>Add Product</h4>
<hr>
<form action="">
<div class="form-group">
<div class="form-group">
</div>
<div class="form-group">
<label for="inputState">Category</label>
<option selected>Choose...</option>
<option>..........</option>
</select>
</div>
</form>
</div>
</div>
<div class="col-md-8">
<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>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}
settings.py
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'inventory',
'USER':'root',
'PASSWORD':'Krishnan@90',
'HOST':'localhost',
'PORT':'3306'
models.py
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)
def __str__(self):
return f'{self.name}-{self.quantity}'
operations\migrations\0001_initial.py
Wait 2-Minutes
Password:Krishnan@90
Password (again):Krishnan@90
50. Start the server and open google and type the address like as following
127.0.0.1:8000/admin
Password : Krishnan@90
admin.site.register(Product)
Category : Stationary
Category : Food
Name : Hp Laptop
Category : Electronics
use inventory;
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
( 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
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:
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):
dashboard\migrations\0004_order.py
Operations to perform:
Running migrations:
Applying dashboard.0004_order... OK
admin.site.register(Product,ProductAdmin)
admin.site.register(Order)
Now the Order- Model will be added into admin page in Dashboard panel
dashboard\migrations\0005_auto_20210602_1553.py
Operations to perform:
Running migrations:
Applying dashboard.0005_auto_20210602_1553... OK
57. To remove the following code from base.html from partial – folder ?
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',
Register.html
urls.py
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 content %}
<div class="container">
<h3>Registration Page!!!</h3>
<hr color="green">
<form method="POST">
{% csrf_token %}
{{ form }}
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
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
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 }}
</form>
70. Run the server and open google chrome and type the following address
127.0.0.1:8000/register
Urls.py
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'),
Login.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
<div class="col-md-6">
<h3>Login Page!!!</h3>
<hr color="green">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
</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
Logout.html
{% extends 'partials/base.html' %}
{% block content%}
<div class="container">
<h3>Logout Page!!!</h3>
<hr color="red">
</div>
75. Run the server and open google chrome and type the address like as following
127.0.0.1:8000/logout
Setting.html
STATIC_URL = '/static/'
STATICFILES_DIRS=[
BASE_DIR / "static/"
STATIC_ROOT =(BASE_DIR/"asert/")
LOGIN_REDIRECT_URL='dashboard-index'
127.0.0.1:8000/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
{% 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">
<span class="navbar-toggler-icon"></span>
</button>
</li>
</ul>
</div>
</li>
<li class="nav-item">
</li>
</ul>
{% else %} <!-- Here if the user not availabe meand the 'register' and 'login' link will
appear on login page-->
</li>
<li class="nav-item">
</li>
</ul>
{% endif %}
</div>
</div>
</nav>
79. Run the server and open google chrome and type the following address
127.0.0.1:8000/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
83. After Run the above page and click register option
84. Now the register page will appear and fill following details
Password : Krishnan@90
( 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
89. Take views.py – File from dashboard-Folder and add some codes
Views.py
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
@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'
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
Index.html
{% extends 'partials/base.html' %}
{% block content%}
<!—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' %}
<div class="containder">
<div class="col-md-6">
<div class="bg-white">
<script>
type: 'pie',
data: {
datasets: [{
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
});
</script>
</div>
</div>
<div class="col-md-6">
<div class="bg-white">
<script>
type: 'bar',
data: {
datasets: [{
label: 'Products',
backgroundColor: [
],
borderColor: [
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
});
</script>
</div>
</div>
</div>
</div>
{% 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
96. Create a new html into dashboard –folder inside of templates folder
Staff_index.html
<div class="container">
<div class="col-md-4">
<div class="card">
<div class="card-header">
Make Request
</div>
<div class="card-body">
<form method="POST">
</form>
</div>
</div>
</div>
<div class="col-md-8">
<div class="card">
<div class="card-header">
Orders Records
</div>
<div class="card-body">
<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
Views.py
def profile(request):
return render(request,'user/profile.html')
urlpatterns = [
path('admin/', admin.site.urls),
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'),
Profile.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
</div>
<div class="col-md-8">
<div class="card">
Profile Page
</div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<hr>
<tbody>
<tr>
<td>Krish</td>
</tr>
<tr>
<td>[email protected]</td>
</tr>
<tr>
<td>+91 9994974215</td>
</tr>
<tr>
<th scope="row">Address:</th>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</div>
{% endblock %}
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
Models.py
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'
user\migrations\0001_initial.py
Operations to perform:
Running migrations:
Applying user.0001_initial... OK
105.Take admin.py – file from user-app-folder
Admin.py
admin.site.register(Profile)
106. Run the server and open google chrome and type the following address
127.0.0.1:800/ admin
After click save and again click on name Heenukrish , there will be currently:path
When click on the currently path , got the error
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
urlpatterns = [
path('admin/', admin.site.urls),
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
Profile.html
<tbody>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<th scope="row">Address:</th>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
</div>
110. Run the server and open google chrome and type the following address
127.0.0.1:8000
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
@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
class UserConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'user'
def ready(self):
113. Run the server and open google chrome and type the following address
127.0.0.1:8000
Click register
Password : Krishnan@90
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
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
Password : Krishnan@90
Click login and click admin profile page ..... now there will be displayed ...e-mail, address,
phone of user
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)
Profile.html
118. create forms.py – file in user-app – folder and add some codes
Forms.py
class UserUpdateForm(forms.ModelForm):
class Meta:
model=User
fields=['username','email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model=Profile
fields=['address','phone','image']
Take views.py – file from User-app- Folder and add some codes
Views.py
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,
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)
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)
Profile_update.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
<div class="col-md-4">
</div>
<div class="col-md-8">
<div class="card">
Profile Page
</div>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<hr>
{% csrf_token %}
{{ user_form| crispy}}
{{ profile_form|crispy}}
</form>
</div>
</div>
</div>
</div>
{% endblock %}
121. Run the server and open google chrome and type the address
127.0.0.1:8000
Password : Krishnan@90
Views.py
@login_required(login_url='user-login')
def product(request):
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>
<tr>
</td>
</tr>
{% endfor %}
</tbody>
125. Run the server and open google chrome and type the following address
126. Create forms.py – file in dashboard- folder and type the following code
Forms.py
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
def product(request):
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 }}
</form>
129. Run the server and open google chrome and type the address
Views.py
item=Product.objects.get(id=pk)
if request.method=="POST":
item.delete()
return redirect('dashboard-product')
return render(request,'dashbaord/product_delete.html')
Urls.py
urlpatterns=[
path('product/',views.product,name='dashboard-product'),
path('product/delete/<int:pk>/',views.product_delete,name='dashboard-product-
delete'),
Product_delete.html
{% extends 'partials/base.html' %}
{% block content %}
<div class="container">
<h3>Delete Item</h3>
<hr color="green">
</div>
<form method="POST">
{% csrf_token %}
{{ form }}
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Product.html
134. Run the server and open google chrome and type the address
Urls.py
urlpatterns=[
path('product/update/<int:pk>/',views.product_update,name='dashboard-product-
update'),
path('order/',views.order,name='dashboard-order'),
Product.html
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":
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)
Product_update.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<h3>Edit Item</h3>
<hr color="green">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
</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
def staff(request):
workers=User.objects.all()
context={
'workers':workers
return render(request,'dashboard/staff.html',context)
Staff.html
<tbody>
<tr>
<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
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'),
staff.html
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)
Staff_details.html
{% extends 'partials/base.html' %}
{% block content%}
{% include 'partials/topnav.html' %}
<div class="container">
<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">
<hr>
<tbody>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<th scope="row">Address:</th>
<td>{{ user.profile.address }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
</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
@login_required(login_url='user-login')
def order(request):
orders=Order.objects.all()
context={
'orders':orders,
return render(request,'dashboard/order.html',context)
order.html
<th scope="col">Order By</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
<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
def index(request):
orders=Order.objects.all()
context={
'orders':orders,
return render(request,'dashboard/index.html',context)
Staff_index.html
{% 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
Forms.py
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
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)
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 }}
</form>
157. Run the server and open google chrome and type the address
127.0.0.1:8000
158. How to set Product has been added – message in Add product page
Views.py
@login_required(login_url='user-login')
def product(request):
if request.method=="POST":
form=ProductForm(request.POST)
if form.is_valid():
form.save()
product_name=form.cleaned_data.get('name')
return redirect('dashboard-product')
else:
form=ProductForm()
context={
'items':items,
'form':form,
return render(request,'dashboard/product.html',context)
product.html
<div class="col-md-4">
{% if message %}
{{ message }}
</div>
{% endif %}
{% endfor %}
160.Run the server and open google chrome and type the address
Views.py
def register(request):
if request.method=='POST':
form=UserCreationForm(request.POST)
if form.is_valid():
form.save()
username=form.cleaned_data.get('username')
return redirect('user-login')
{% if message %}
{{ message }}
</div>
{% endif %}
{% endfor %}
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)
type: 'pie',
data: {
datasets: [{
label: 'Orders',
type: 'bar',
data: {
datasets: [{
label: 'Products',
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,
Topnav.html
<h3>{{ workers_count}}</h3>
Views.py
def product(request):
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,
Topnav.html
def product(request):
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):
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,
<h3>{{ product_count}}</h3>
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,
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'),
Login.html
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
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.
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.
http://127.0.0.1:8000/password_reset_confirm/Mg/ao6g99-
0e0e36686407a41115a1e42b189e7c24/
New Password :
Confirm Password :
Your password has been set. You may go ahead and log in now.
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'),
Password_reset.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
{% if message %}
{{ message }}
</div>
{% endif %}
{% endfor %}
<hr color="green">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
</form>
</div>
</div>
</div>
</div>
{% endblock%}
password_reset_done.html
{% extends 'partials/base.html' %}
{% block content%}
<div class="container">
<hr color="red">
<h4>A mail has been sent to the email address you provided.
</div>
</div>
</div>
{% endblock%}
Password_reset_confirm.html
{% extends 'partials/base.html' %}
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
{% if message %}
{{ message }}
</div>
{% endif %}
{% endfor %}
<hr color="green">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
</form>
</div>
</div>
</div>
</div>
{% endblock%}
Password_reset_complete.html
{% extends 'partials/base.html' %}
{% block content%}
<div class="container">
<hr color="greeen">
</div>
</div>
</div>
</div>
{% endblock%}