Module 4 Lab Manual
Module 4 Lab Manual
Module 4
Web Designing
Lab Manual
Activities:
1. Install Python software in the system and print a string using print statement (4Hrs)
2. Print given string using indentation (space between characters) (1Hrs)
3. Define Integer Variables, floating variables and string variables ( 1Hr)
4. Write a program to add numbers and strings to the correct list using the append list method (
2Hrs)
5. Write a python program to add, subtract, multiply and divide given two numbers by using
arithmetic operators(2Hrs)
6. Write a python program multiplying strings to form string with repeating sequence (2Hrs)
7. Write a Python program to get the largest number from a list by using max and mini commands
(1Hr)
8. Write a Python program to find whether a given number (accept from the user) is even or odd by
using if else command (2Hrs)
9. Write a Python program to create a histogram from a given list of integers by using for while
loop (1Hrs)
10. Write a Python program to compute the greatest common divisor (GCD) of two positive integers
by using loops (2Hrs)
11. Write a Python program to get the least common multiple (LCM) of two positive integers using if
else and while commands(2Hrs)
12. Write a Python program to sort (ascending and descending) a dictionary by value (2Hrs)
13. Write a Python program to create a tuple. (2Hrs)
14. Write a Python program to create a tuple with different data types (1Hrs)
15. Write a Python program to create a dictionary and perform functional operations (2Hrs)
16. Write a Python program to find maximum and the minimum value in a set. (1 Hrs)
17. Write a python program to copy content of a text file to another file (3Hrs)
18. Write a python program to copy content of an image/video file to another file (3Hrs)
19. Write program to demonstrate exception handling while creating file, reading file, writing file and
deleting a file(4 Hrs)
20. Write a program to demonstrate file handling in connecting to database and performing operations ( 2 Hrs
)
21. Create student database in mysql and connect using python (3 Hrs)
22. Perform CRUD operations on mysql database using python (4 Hrs)
23. Perform CRUD operations on MongoDB database using python (3 Hrs)
24. Create a student class with related data elements and methods. Write functionalities for basic operations
of student in a college (3Hrs)
25. With student class already created, perform database crud operations including validation of data while
writing to DB and when reading from DB (4 Hrs)
26. Create a simple python Flask app with at least 3 basic routes (4 Hrs)
Learning outcome – Web Application with Django
Framework
After achieving this learning outcome, a student will be able to make websites, web servers, game
frameworks, desktop and CLI applications, and IDE using Python. In order to achieve this learning
outcome, a student has to complete the following:
Activities:
Skills related to working with django framework (120 hr)
1. Install django framework libraries in python and test for installation
2. Setup first django application
3. Creating django application with MVT architecture
4. Create django application that handles file uploading
5. Create django application that reads data from CSV and display on page
6. Create django application that reads data from JSON and display on page
7. Creating django application which implement CRUD operations over database
8. Create django application validates user credentials on login page
9. Create admin panel using django, using AJAX
10. Perform crud operations in django app using AJAX at single page
11. Create django application which sends email to any recipient
Activity 1
Aim: Install Python and write a Python program to print a string using the print statement
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 4 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Windows/Linux OS - Ubuntu 18.04 LTS
2. Python Software
Program:
Installation steps for Linux:
● Ctrl+Alt+T Open Terminal
● Type Command : sudo apt-get update
● Start programming
Installation Steps for Windows:
● Install Python software in the system.
● Open the browser and type the python.org/downloads.
● Click on download .
● Choice either Windows x86-64 executable installer for 64-bit or Windows x86 executable
installer for 32-bit.
● After downloading a file the below page will appear.
Figure 1: Installing
Figure 2: Installed successfully
print ("Welcome to Python Practical") #print() is a library function to display the text on screen
Output/Results snippet:
References:
1. https://www.ics.uci.edu/~pattis/common/handouts/pythoneclipsejava/python.html
Activity 2
Aim: Write a python program to print given string using indentation (space between characters)
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
print("\n\n\th e l l o \n \t \t \t w o r l d \n") # tab \t, new line \n and space is used
Output/Results snippet:
References:
1. https://stackoverflow.com/questions/18756510/printing-with-indentation-in-python
Activity 3
Aim: Define Integer Variables, floating variables and string variables.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
myint = 7 # declare integer variable
print(myint) # print the value of the variable
myfloat = 7.0 # declare floating variable
print(myfloat)
myfloat = float(7)
print(myfloat)
mystring = 'hello' # declare string variable
print(mystring)
mystring = "hello"
print(mystring)
Output:
7
7.0
7.0
hello
hello
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 4
Aim: Write a program to add numbers and strings to the correct list using the append list method.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
numbers = [1,2,3]
strings = ["Hello","World"] # declare and initialize list
names = ["John", "Eric", "Jessica"]
second_name = names[1]
print(numbers) # print the values of list
print(strings)
print("The second name on the names list is %s" % second_name)
Output:
[1, 2, 3]
['Hello', 'World']
The second name on the names list is ['Eric']
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 5
Aim: Write a python program to add, subtract, multiply and divide given two numbers by using
arithmetic operators.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Exit");
choice = int(input("Enter your choice: ")); # take input from console
if (choice>=1 and choice<=4): # taking input from 1 to 4
print("Enter two numbers: ");
num1 = int(input());
num2 = int(input());
if choice == 1: # perform addition if 1
res = num1 + num2;
print("Result = ", res);
elif choice == 2: # perform subtraction if 2
res = num1 - num2;
print("Result = ", res);
elif choice == 3: # perform multiplication if 3
res = num1 * num2;
print("Result = ", res);
elif choice == 4: # perform division if 4
res = num1 / num2;
print("Result = ", res);
elif choice == 5:
exit(); # exit if 5
else:
print("Wrong input..!!"); # print message for any other input
Output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter two numbers:
2
4
('Result = ', 6)
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 6
Aim: Write a python program multiplying strings to form a string with repeating sequence.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
x = 'Welcome '
y = 'python '
print ((x+y)*5) # printing the concatenated strings 5 times
Output:
Welcome python Welcome python Welcome python Welcome python Welcome python
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 7
Aim: Write a Python program to get the largest number from a list by using max and min commands.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
list = [1, 2, 3]
print (max(list)) # max() finds the maximum among values
print (min(list)) # min() finds the minimum among values
Output:
3
1
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 8
Aim: Write a Python program to find whether a given number (accept from the user) is even or odd
by using if else command.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
num = int(input("Enter a number: ")) # taking input from console
mod = num % 2 # extracting the remainder value of input
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
Output:
Enter a number: 5
This is an odd number.
Enter a number: 2
This is an even number.
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 9
Aim: Write a Python program to create a histogram from a given list of integers by using for while
loop.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
def histogram( items ): # create function
for n in items: # for loop through values of n
output = ''
times = n
while( times > 0 ): # check condition of counter
output += '*'
times = times–1 # decrement the counter
print(output) # print the output
histogram([2, 3, 6, 5])
Output:
**
***
******
*****
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 10
Aim: Write a Python program to compute the greatest common divisor (GCD) of two positive
integers by using loop
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
def gcd(x, y): # create function gcd()
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1): # for loop from y/2 to 0 increment -1
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print(gcd(12, 17)) # print the gcd value
print(gcd(4, 6))
Output:
1
2
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 11
Aim: Write a Python program to get the least common multiple (LCM) of two positive integers using
if else and while commands.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
1. Laptop/Computer with Linux OS - Ubuntu 18.04 LTS
2. Python3 Software
Program:
def lcm(x, y): # define function
if x > y:
z=x
else:
z=y
while(True):
if((z % x == 0) and (z % y == 0)): # check if both conditions are true
lcm = z
break
z += 1
return lcm
print(lcm(4, 6)) # print the lcm value
print(lcm(15, 17))
Output:
12
255
References:
● https://www.tutorialspoint.com/python/python_overview.htm
● https://www.w3schools.com/python/
● https://www.javatpoint.com/python-tutorial
Activity 12
Aim: Write a Python program to sort (ascending and descending) a dictionary by value
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
Program:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)
print('Dictionary in descending order by value : ',sorted_d)
Output/Results snippet:
References:
● https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-1
.php
● https://stackoverflow.com/questions/20577840/python-dictionary-sorting-in-descending-order-ba
sed-on-values/41866830
● https://www.youtube.com/watch?v=trWU2GDqXS4
● https://www.youtube.com/watch?v=-UGJvJNZ7i4
Activity 13
Aim: Write a Python program to create a tuple.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# tuple having integers
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed data types
# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
# Output: ("user", [8, 4, 6], (1, 2, 3))
my_tuple = ("user", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# tuple can be created without parentheses
# also called tuple packing
# Output: 3, 4.6, "data"
my_tuple = 3, 4.6, "data"
print(my_tuple)
# tuple unpacking is also possible
Output/Results snippet:
References:
● https://www.w3schools.com/python/python_tuples.asp
● https://www.w3resource.com/python-exercises/tuple/python-tuple-exercise-3.php
● https://www.programiz.com/python-programming/tuple
● https://www.geeksforgeeks.org/tuples-in-python/
Activity 14
Aim: Write a Python program to create a tuple with different data types
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
Program:
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
Output/Results snippet:
References:
● https://www.w3resource.com/python-exercises/tuple/python-tuple-exercise-2.php
● https://www.youtube.com/watch?v=eXnZfHwzSiI
● http://python.mykvs.in/Programs/class%20xi/cs/tuple%20p.pdf
Activity 15
Aim: Write a Python program to create a set
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
#A new empty set
setx = set()
print(setx)
set()
#A non empty set
n = set([0, 1, 2, 3, 4, 5])
print(n)
Output/Results snippet:
References:
● https://www.w3schools.com/python/python_sets.asp
● https://www.geeksforgeeks.org/python-sets/
● https://www.youtube.com/watch?v=MEPlLAjPvXY
Activity 16
Aim: Write a Python program to add member(s) in a set
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
Program:
#A new empty set
color_set = set()
#Add a single member
color_set.add("Red")
print(color_set)
#Add multiple items
color_set.update(["Blue", "Green"])
print(color_set)
Output/Results snippet:
References:
● https://www.w3resource.com/python-exercises/sets/python-sets-exercise-3.php
● https://www.geeksforgeeks.org/set-add-python/
Activity 17
Aim: Write a Python program to find maximum and the minimum value in a set.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 1 hour
List of Hardware/Software requirements:
Program:
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
Output/Results snippet:
References:
● https://www.w3resource.com/python-exercises/sets/python-sets-exercise-14.php
● https://www.geeksforgeeks.org/python-maximum-minimum-set/
Activity 18
Program:
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find the length use len()
print(len(seta))
Output/Results snippet:
References:
● https://www.w3resource.com/python-exercises/sets/python-sets-exercise-15.php
● https://www.edureka.co/blog/python-list-length/
● https://www.youtube.com/watch?v=hbVekSSSzVM
Activity 19
Aim: Write a Python program to convert temperatures to and from Centigrade to Fahrenheit
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
Fahrenheit = float(input("Enter a temperature in Fahrenheit: "))
Celsius = (Fahrenheit - 32) * 5.0/9.0
print ("Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C")
Celsius = float(input("Enter a temperature in Celsius: "))
Fahrenheit = 9.0/5.0 * Celsius + 32
print ("Temperature:", Celsius, "Celsius = ", Fahrenheit, " F")
Output/Results snippet:
References:
● https://beginnersbook.com/2019/05/python-Program-to-convert-celsius-to-fahrenheit-and-vice-ve
rsa/
● https://www.youtube.com/watch?v=_fxLlOO0Pts
● https://www.Programming-techniques.com/2019/03/python-Program-to-convert-celsius-to-fahren
heit-and-vice-versa.html
Activity 20
Aim: Write a python program to find Fibonacci series
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
pterms = int(input("How many terms? "))
n1 = 0
n2 = 1
count = 0
if pterms <= 0:
print("Please enter a positive integer")
elif pterms == 1:
print("Fibonacci sequence upto",pterms,":")
print(n1)
else:
print("Fibonacci sequence upto",pterms,":")
while count < pterms:
print(n1,end='\n')
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output/Results snippet:
Activity 21
Aim: Write a python program to find factorial using function in Python IDLE.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
# Function name using recursion_function(n)
def recursion_factorial(n):
if n == 1:
return n
else:
return n*recursion_factorial(n-1)
# read the value of input for factorial number
num = int(input('\n Enter your factorial number '))
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist its negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recursion_factorial(num))
Output/Results snippet
Activity 22
Aim: Write a python program to find whether the given string is palindrome or not by using function.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
#enter input of the word
Word = str(input("Enter a word :"))
#check the word whether palindrome or not
if(Word==Word[::-1]):
print("Your Word is palindrome")
else:
print("Your Word isn't palindrome")
Output/Results Snippet
References
● https://docs.python.org/3/tutorial/
● https://www.tutorialsteacher.com/python
● https://realpython.com/
Activity 23
Aim: Write a python class to reverse a string word by word.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
# Python program to Reverse each word of a string
# function definition
def reverseword(input_word):
w = input_word.split(" ")
# Splitting the string into a list of words
# reversing each word and creating a new list of words
nw = [i[::-1] for i in w]
# Joining the new list of words to form a new string
ns = " ".join(nw)
return ns
# main() method
input_word = input("Enter the string: ")
print(reverseword(input_word))
Output/Result Snippet
References
● https://docs.python.org/3/tutorial/
● https://www.tutorialsteacher.com/python
● https://realpython.com/
Activity 24
Aim: Write a python class named as circle by a radius and two methods of computer area and
perimeter of a circle.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
#using math package
import math
#using math function calculate the value
class circle():
def init (self,radius):
self.radius=radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius
#read value of area input from user
value_of_circle=int(input("Enter radius of circle: "))
#Object for Class
obj=circle(value_of_circle)
print("Area of circle:",round(obj.area(),2))
print("Perimeter of circle:",round(obj.perimeter(),2))
Output/Result Snippet
Activity 25
Aim: Write a python program to sort a list of elements using bubble sort algorithm.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
# Python Program for Bubble Sort
def bubblesort(a, number):
for i in range(number -1):
for j in range(number - i - 1):
if(a[j] > a[j + 1]):
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
a = []
number = int(input("Please Enter the Total Number of Elements : "))
for i in range(number):
value = int(input("Please enter the %d Element of List1 : " %i))
a.append(value)
bubblesort(a, number)
print("The Sorted List in Ascending Order : ", a)
Note: Here, we are using Nested for Loop to iterate each element in a given List. Inside the loop, we
are using the If statement to sort items in an ascending order using Bubble Sort
Output Snippet
Activity 26
Aim: Write a python program to copy content of a file to another file (3Hrs)
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
#Input files for Read data
#Output file to copy content from input file
with open("input.txt" ,"r") as f:
with open("output.txt", "w") as f1:
#writes content from existing to new file
for line in f:
f1.write(line)
#display content of copying text
print("Copy content text is : ",line)
#close files
f.close()
f1.close()
Output Snippet
References
● https://docs.python.org/3/tutorial/
● https://www.tutorialsteacher.com/python
● https://realpython.com/
Activity 27
Aim: Write a python program to find the frequency of words in a file.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hour
List of Hardware/Software requirements:
Program:
#import counter for read data
from collections import Counter
def word_count(fname):
#Open a file and read text
with open(fname) as f:
#Separating a text word by word using split()
return Counter(f.read().split())
print("Number of words in the file :",word_count("output.txt"))
Output Snippet
References
● https://docs.python.org/3/tutorial/
● https://www.tutorialsteacher.com/python
● https://realpython.com/
Activity 28
Aim: Write a python program to illustrate exception handling
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 4 hours
List of Hardware/Software requirements:
Program:
import sys
list=['boy', 'cat',0 ,14.3]
for entry in list:
try:
print("the entry is:" , entry)
r=1/int(entry)
except(ValueError):
print("Hey a ValueError exception occured")
except(ZeroDivisionError):
print("Hey a ZeroDivisionError exception occured")
except:
print("some error occur")
print("the recipocal of the entry is ",r)
Output Snippet
References
● https://blog.ineuron.ai/File-Handling-and-Exception-Handling-in-PYTHON-Yx6AqWHtOF
Activity 29
Aim: Develop a python code to read a text file, copy the contents to another file after
removing the blank lines.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 2 hours
List of Hardware/Software requirements:
Program:
fh = open('Blank.txt','r')
h = open('BlankRemove.txt','w')
b = fh.readlines()
for line in b :
print(line,end = '')
for line in b :
if(len(line)>0) :
line = line.lstrip()
h.write(line)
fh.close()
h.close()
h = open('BlankRemove.txt','r')
y = h.read()
print(y)
h.close()
Output Snippet
References
https://www.geeksforgeeks.org/python-file-handling/
Activity 30
Aim: Create a database in mysql and connect using python
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 3 hours
List of Hardware/Software requirements:
Program:
# importing required libraries
import mysql.connector
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="gfg"
)
# creating database
cursorObject.execute("CREATE DATABASE geeks4geeks")
Output Snippet
References
https://www.geeksforgeeks.org/python-mysql-create-database/
Activity 31
Aim: Perform CRUD operations on mysql database using python
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 4 hours
List of Hardware/Software requirements:
Program:
# importing required library
import mysql.connector
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""
# table created
cursorObject.execute(studentRecord)
Output Snippet
References
https://www.geeksforgeeks.org/python-mysql-create-database/
Activity 32
Aim: Perform CRUD operations on MongoDB database using python
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 3 hours
List of Hardware/Software requirements:
Program:
# importing required library
import pymongo
connection_url="mongodb://localhost:27017/”
client.list_database_names()
# creating collection
collection_name=”computer science”
collection=student_db[collection_name]
student_db.list_collection_names()
#Inserting document
document={"Name":"Raj",
"Roll No ": 153,
"Branch ": "CSE"}
collection.insert_one(document)
#Reading a document
query={"Name":"Raj"}
print(collection.find_one(query))
#updating
query={"Roll No":{"$eq":153}}
present_data=collection.find_one(query)
new_data={'$set':{"Name":'Ramesh'}}
collection.update_one(present_data,new_data)
# deleting
query={“Roll No”:153}
collection.delete_one(query)
Output Snippet
References
https://medium.com/analytics-vidhya/crud-operations-in-mongodb-using-python-49b7850d627e
Activity 33
Aim: Create a class with related data elements and methods. Write functionalities for basic operations
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 3 hours
List of Hardware/Software requirements:
Program:
import datetime # we will use this for date objects
class Person:
self.address = address
self.telephone = telephone
self.email = email
def age(self):
today = datetime.date.today()
age = today.year - self.birthdate.year
return age
person = Person(
"Jane",
"Doe",
datetime.date(1992, 3, 12), # year, month, day
"No. 12 Short Street, Greenville",
"555 456 0987",
"[email protected]"
)
print(person.name)
print(person.email)
print(person.age())
Output Snippet
References
https://python-textbok.readthedocs.io/en/1.0/Classes.html
Activity 34
Aim: Python program using a flag to validate if the input given by the user is an integer.#Datatype check.
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 4 hours
List of Hardware/Software requirements:
Program:
#Declare a variable validInt which is also considered as flag and set it to false
validInt = False
#Consider the while condition to be true and prompt the user to enter the input
while not validInt:
#The user is prompted to enter the input
age1 = input('Please enter your age ')
#The input entered by the user is checked to see if it’s a digit or a number
if age1.isdigit():
#The flag is set to true if the if condition is true
validInt = True
else:
print('The input is not a valid number')
#This statement is printed if the input entered by the user is a number
print('The entered input is a number and that is ' + str(age1))
Output Snippet
References
https://www.educba.com/python-validation/
Activity 35
Aim: Create a simple python Flask app with at least 3 basic routes
Learning outcome: Able to make websites, web servers, game frameworks, desktop and CLI
applications, and IDE using Python.
Duration: 4 hours
List of Hardware/Software requirements:
Program:
@app.route('/')
# ‘/’ URL is bound with hello_world() function.
def hello_world():
return 'Hello World'
if __name__ == '__main__':
References
https://www.geeksforgeeks.org/flask-creating-first-simple-application/
Activity 1
Aim: Install Django framework libraries in python and test for installation
Learning outcome: Able to install Django.
Duration: 3 hour
List of Hardware/Software requirements:
1. VSCode
2. Python
Output/Results snippet:
Activity 2
Aim: Setup first Django application
Learning outcome: Able to display Hello World in the web browser using Django.
Duration: 3 hour
List of Hardware/Software requirements:
• VSCode
• Python
1. In the VS Code Terminal with your virtual environment activated, run the administrative
utility's startapp command in your project folder (where manage.py resides):
The command creates a folder called hello that contains a number of code files and one subfolder. Of
these, you frequently work with views.py (that contains the functions that define pages in your web
app) and models.py (that contains classes defining your data objects). The migrations folder is used by
Django's administrative utility to manage database versions as discussed later in this tutorial. There
are also the files apps.py (app configuration), admin.py (for creating an administrative interface),
and tests.py (for creating tests), which are not covered here.
2. Modify hello/views.py to match the following code, which creates a single view for the app's home
page:
def home(request):
3. Create a file, hello/urls.py, with the contents below. The urls.py file is where you specify patterns to
route different URLs to their appropriate views. The code below contains one route to map root URL
of the app ("") to the views.home function that you just added to hello/views.py:
4. The web_project folder also contains a urls.py file, which is where URL routing is actually handled.
Open web_project/urls.py and modify it to match the following code (you can retain the instructive
comments if you like). This code pulls in the app's hello/urls.py using django.urls.include, which keeps
the app's routes contained within the app. This separation is helpful when a project contains multiple
apps.
urlpatterns = [
path("", include("hello.urls")),
path('admin/', admin.site.urls)
Output/Results snippet:
Activity 3
Aim: Creating Django application with MVT architecture
Learning outcome: Able to understand creating Django using MVT.
Duration: 5 hour
List of Hardware/Software requirements:
1. Django
2. Python
3. VS Code
Code/Program/Procedure (with comments):
Step: Create Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and one way to manage a virtual
environment is venv, which is included in Python.
With venv, you can create a virtual environment by typing this in the command prompt, remember to navigate to
where you want to create your project:
Windows:
py -m venv myproject
Unix/MacOS:
python -m venv myproject
This will set up a virtual environment, and create a folder named "myproject" with subfolders and files, like this:
myproject
Include
Lib
Scripts
pyvenv.cfg
Then you have to activate the environment, by typing this command:
Windows:
myproject\Scripts\activate.bat
Unix/MacOS:
source myproject/bin/activate
Once the environment is activated, you will see this result in the command prompt:
Windows:
(myproject) C:\Users\Your Name>
Unix/MacOS:
(myproject) ... $
Note: You must activate the virtual environment every time you open the command prompt to work on your project.
These are all files and folders with a specific meaning, you will learn about some of them later in this tutorial, but for
now, it is more important to know that this is the location of your project, and that you can start building applications
in it.
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s):
admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 02, 2021 - 13:14:51
Django version 3.2.9, using settings 'myworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open a new browser window and type 127.0.0.1:8000 in the address bar.
The result:
Step -Django Create App
Create App
I will name my app members.
Start by navigating to the selected location where you want to store the app, and run the command below.
If the server is still running, and you are not able to write commands, press [CTRL] [BREAK] to stop the server and
you should be back in the virtual environment.
py manage.py startapp members
Django creates a folder named members in my project, with this content:
myworld
manage.py
myworld/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
These are all files and folders with a specific meaning. You will learn about most of them later in this tutorial.
First, take a look at the file called views.py.
def index(request):
return HttpResponse("Hello world!")
This is a simple example on how to send a response back to the browser.
But how can we execute the view? Well, we must call the view via a URL.
URLs
Create a file named urls.py in the same folder as the views.py file, and type this code in it:
members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
The urls.py file you just created is specific for the members application. We have to do some routing in the root
directory myworld as well. This may seem complicated, but for now, just follow the instructions below.
There is a file called urls.py on the myworld folder, open that file and add the include module in the import statement,
and also add a path() function in the urlpatterns[] list, with arguments that will route users that comes in via
127.0.0.1:8000/members/.
Then your file will look like this:
myworld/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('members/', include('members.urls')),
path('admin/', admin.site.urls),
]
If the server is not running, navigate to the /myworld folder and execute this command in the command prompt:
py manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
Step-Django Templates
Templates
In the Django Intro page, we learned that the result should be in HTML, and it should be created in a template, so let's
do that.
Create a templates folder inside the members folder, and create a HTML file named myfirst.html.
The file structure should be something like this:
myworld
manage.py
myworld/
members/
templates/
myfirst.html
<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
def index(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be able to work with more complicated stuff than "Hello World!", We have to tell Django that a new app is created.
This is done in the settings.py file in the myworld folder.
Look up the INSTALLED_APPS[] list and add the members app like this:
myworld/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members.apps.MembersConfig'
]
Then run this command:
py manage.py migrate
Which will produce this output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myproject)C:\Users\Your Name\myproject\myworld>
Start the server by navigating to the /myworld folder and execute this command:
py manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
The result should look like this:
References - https://www.w3schools.com/django/django_create_project.php
https://www.w3schools.com/django/django_create_app.php
https://www.w3schools.com/django/django_views.php
https://www.w3schools.com/django/django_templates.php
Activity 4
Aim: Create Django application that handles file uploading
Learning outcome: Able to understand file handling and how to upload file .
Duration: 4 hour
List of Hardware/Software requirements:
1. Django
2. Python
3. VS Code
Template (index.html)
It will create an HTML form which contains a file input component.
<body>
<form method="POST" class="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
Form (forms.py)
from django import forms
class StudentForm(forms.Form):
firstname = forms.CharField(label="Enter first name",max_length=50)
lastname = forms.CharField(label="Enter last name", max_length = 10)
email = forms.EmailField(label="Enter Email")
file = forms.FileField() # for creating file input
View (views.py)
Here, one extra parameter request.FILES is required in the constructor. This argument contains the uploaded
file instance.
from django.shortcuts import render
from django.http import HttpResponse
from myapp.functions.functions import handle_uploaded_file
from myapp.form import StudentForm
def index(request):
if request.method == 'POST':
student = StudentForm(request.POST, request.FILES)
if student.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponse("File uploaded successfuly")
else:
student = StudentForm()
return render(request,"index.html",{'form':student})
Specify URL (urls.py)
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
]
Upload Script (functions.py)
This function is used to read the uploaded file and store at provided location. Put this code into the
functions.py file. But first create this file into the project.
def handle_uploaded_file(f):
with open('myapp/static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
Now, create a directory upload to store the uploaded file. Our project structure looks like below.
Initially, this directory is empty. so, let's upload a file to it and later on it will contain the uploaded file.
Start Server
python manage.py runserver
Output
Submit this form and see the upload folder. Now, it contains the uploaded file.
References - https://www.javatpoint.com/django-file-upload
Activity 5
Aim: Create Django application that reads data from CSV and display on page
Learning outcome: Able to understand basic computer network technology.
Duration: 5 hour
List of Hardware/Software requirements:
1. Django
2. Python
3. VSCode
def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(
content_type='text/csv',
headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'},
)
writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
return response
The code and comments should be self-explanatory, but a few things deserve a mention:
● The response gets a special MIME type, text/csv. This tells browsers that the document is a CSV file, rather
than an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will
result in ugly, scary gobbledygook in the browser window.
● The response gets an additional Content-Disposition header, which contains the name of the CSV file. This
filename is arbitrary; call it whatever you want. It’ll be used by browsers in the “Save as…” dialog, etc.
● You can hook into the CSV-generation API by passing response as the first argument to csv.writer. The
csv.writer function expects a file-like object, and HttpResponse objects fit the bill.
● For each row in your CSV file, call writer.writerow, passing it an iterable.
● The CSV module takes care of quoting for you, so you don’t have to worry about escaping strings with quotes
or commas in them. Pass writerow() your raw strings, and it’ll do the right thing.
Streaming large CSV files¶
When dealing with views that generate very large responses, you might want to consider using Django’s
StreamingHttpResponse instead. For example, by streaming a file that takes a long time to generate you can avoid a load
balancer dropping a connection that might have otherwise timed out while the server was generating the response.
In this example, we make full use of Python generators to efficiently handle the assembly and transmission of a large CSV
file:
import csv
class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value
def some_streaming_csv_view(request):
"""A view that streams a large CSV file."""
# Generate a sequence of rows. The range is based on the maximum number of
# rows that can be handled by a single sheet in most spreadsheet
# applications.
rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
return StreamingHttpResponse(
(writer.writerow(row) for row in rows),
content_type="text/csv",
headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'},
)
def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(
content_type='text/csv',
headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'},
)
# The data is hard-coded here, but you could load it from a database or
# some other source.
csv_data = (
('First row', 'Foo', 'Bar', 'Baz'),
('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"),
)
t = loader.get_template('my_template_name.txt')
c = {'data': csv_data}
response.write(t.render(c))
return response
The only difference between this example and the previous example is that this one uses template loading instead of the
CSV module. The rest of the code – such as the content_type='text/csv' – is the same.
Then, create the template my_template_name.txt, with this template code:
{% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes
}}", "{{ row.4|addslashes }}"
{% endfor %}
This short template iterates over the given data and displays a line of CSV for each row. It uses the addslashes template
filter to ensure there aren’t any problems with quotes.
class CSVPageView(TemplateView):
template_name = "csv_home.html"
csv_app/templates/csv_home.html
<!DOCTYPE html>
<html>
<head><title>CSV Examples</title></head>
<body>
<h3>CSV Example - Read Write Examples</h3>
<ul>
<li>Write Operation
<ul>
<li>
<a href="{% url 'csv_simple_write' %}">Simple CSV Write Operation</a>
</li>
<li>
<a href="{% url 'csv_dictionary_write' %}">Writing CSV File From a Dictionary</a>
</li>
<li>
<a href="{% url 'csv_database_write' %}">Database Data CSV Write Operation</a>
</li>
</ul>
</li>
<br>
<li>Read Operation
<ul>
<li>
<a href="{% url 'csv_simple_read' %}">Simple CSV Read Operation</a>
</li>
</ul>
</li>
</ul>
{{csv_data}}
{% if csv_data %}
sad
{{csv_data}}
{% endif %}
</body>
</html>
Note: if you run the above file it will give an error because we have not created URLs. We are going to
create those URLs below in Read/Write operation code.
Create a file named urls.py in your csv_app folder and the code. Note the URLs of these apps can be created
here.
from django.urls import path
from csv_app import views
urlpatterns = [
path('', views.CSVPageView.as_view(), name='csv_home_page'),
]
The last thing, we need to import csv_app/urls.py in the main folder django_csv/urls.py. Edit
django_csv/urls.py and django_csv/urls.py should look like below:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(csv_app_urls))
]
Python CSV Library Code Explanation
● HttpResponse(content_type='text/csv') – This tells browsers that the document is a CSV file,
instead of HTML file.
● response['Content-Disposition'] = 'attachment; filename="csv_simple_write.csv"' – This contains
CSV filename and downloads files with that name.
● Hooking into the CSV-generation API is easy: simply pass response because of the initial
argument to csv.writer. The csv.writer perform expects a file-like object, and HttpResponse
objects match the bill.
● writer.writerow(['first_name', 'last_name', 'phone_number', 'country']) – Will add/write a row in
your csv file.
Simple CSV Export/Write Operation
# csv_app/views.py
import csv
from django.http import HttpResponse
writer = csv.writer(response)
writer.writerow(['first_name', 'last_name', 'phone_number', 'country'])
writer.writerow(['Huzaif', 'Sayyed', '+919954465169', 'India'])
writer.writerow(['Adil', 'Shaikh', '+91545454169', 'India'])
writer.writerow(['Ahtesham', 'Shah', '+917554554169', 'India'])
import csv
from django.http import HttpResponse
# Writing CSV File From a Dictionary
def csv_dictionary_write(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="csv_dictionary_write.csv"'
fieldnames = ['first_name', 'last_name', 'phone_number', 'country']
writer = csv.DictWriter(response, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name':'Huzaif', 'last_name':'Sayyed', 'phone_number':'+919954465169', 'country':'India'})
writer.writerow({'first_name':'Adil', 'last_name':'Shaikh', 'phone_number':'+91545454169', 'country':'India'})
writer.writerow({'first_name':'Ahtesham', 'last_name':'Shah', 'phone_number':'+917554554169', 'country':'India'})
import csv
from django.http import HttpResponse
from .models import UserDetail
def csv_database_write(request):
writer = csv.writer(response)
writer.writerow(['first_name', 'last_name', 'phone_number', 'country'])
def csv_simple_read(request):
path = os.path.dirname(__file__)
file = os.path.join(path, 'csv_readfile.csv')
The above code will read a CSV file and display it in Console and then redirect to the home page.
References- https://docs.djangoproject.com/en/4.0/howto/outputting-csv/
https://studygyaan.com/django/how-to-export-csv-file-with-django
https://github.com/studygyaan/How-to-Create-CSV-File-With-Django
Activity 6
Aim: Create Django application that reads data from JSON and display on page.
Learning outcome: Able to understand how to reads data from JSON and display on page.
Duration: 3 hour
List of Hardware/Software requirements:
1. Django
2. Python
3. VS Code
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. The official Internet
media type for JSON is application/json. The JSON filename extension is .json. It is easy for
humans to read and write and for machines to parse and generate.
Django JsonResponse
JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default
Content-Type header is set to application/json. The first parameter, data, should be a dict instance. If
the safe parameter is set to False, any object can be passed for serialization; otherwise only dict
instances are allowed.
Django JsonResponse example
In the following example, we create a Django application that sends a file to the client. The file is a
JPEG image, which is located in the images directory in the project root directory.
$ mkdir jsonresponse
$ cd jsonresponse
$ mkdir src
$ cd src
We create the project and the and src directories. Then we locate to the src directory.
$ django-admin startproject jsonresponse .
urlpatterns = [
path('admin/', admin.site.urls),
path('sendjson/', send_json, name='send_json'),
]
We add a new route page; it calls the send_json() function from the views.py module.
src/jsonresponse/views.py
from django.http import JsonResponse
def send_json(request):
Inside send_json(), we define a list of dictionaries. Since it is a list, we set safe to False. If we did
not set this parameter, we would get a TypeError with the following message:
In order to allow non-dict objects to be serialized set the safe parameter to False.
References: https://zetcode.com/django/jsonresponse/
Activity 7
Aim: Creating Django application which implement CRUD operations over database
Learning outcome: Able to create model and perform CRUD operations.
Duration: 6 hour
List of Hardware/Software requirements:
1. Django
2. Python
3. VS Code
class Members(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, "firstname" is a Text field, and will contain the first name of the members.
The second field, "lastname" is also a Text field, with the members' last name.
Both "firstname" and "lastname" is set up to have a maximum of 255 characters.
Then navigate to the /myworld/ folder and run this command:
py manage.py makemigrations members
Which will result in this output:
Migrations for 'members':
members\migrations\0001_initial.py
- Create model Members
View in Browser
We want to see the result in a web page, not in a Python shell environment.
To see the result in a web page, we can create a view for this particular task.
In the members app, open the views.py file, if you have followed the previous chapters of this tutorial, it should look
like this:
members/views.py:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('myfirst.html')
HttpResponse(template.render())
Change the content in the views.py file to look like this instead:
members/views.py:
from django.http import HttpResponse
from django.template import loader
from .models import Members
def index(request):
mymembers = Members.objects.all().values()
output = ""
for x in mymembers:
output += x["firstname"]
return HttpResponse(output)
As you can see in line 3, the Members model is imported, and the index view does the following:
● makes a mymembers object with all the values of the Members model.
● Loops through all items in the mymembers object to build a string with all the firstname values.
● Returns the string as output to the browser.
See the result in your browser. If you are still in the Python shell, write this command to exit the shell:
>>> quit()
Navigate to the /myworld/ folder and type this to start the server:
py manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
The result:
Adding Template
To add some HTML around the values, we will create a template for the application.
All templates must be located in the templates folder off your app, if you have not already created a templates folder,
do it now.
In the templates folder, create a file named index.html, with the following content:
members/templates/index.html:
<h1>Members</h1>
<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>
Did you notice the {% %} and {{ }} parts? They are called template tags.
Template tags allows you to perform logic and render variables in your templates, you will learn more about template
tags later.
Modify the View
Change the index view to include the template:
members/views.py:
from django.http import HttpResponse
from django.template import loader
from .models import Members
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
The index view does the following:
● Creates a mymembers object with all the values of the Members model.
● Loads a the index.html template.
● Creates an object containing the mymember object.
● Sends the object to the template.
● Outputs the HTML that is rendered by the template.
In the browser window, type 127.0.0.1:8000/members/ in the address bar.
The result:
Template
Start by adding a link in the members template:
members/templates/index.html:
<h1>Members</h1>
<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>
<p>
<a href="add/">Add member</a>
</p>
The result will look like this:
New Template
Add a new template in the templates folder, named add.html:
members/templates/add.html:
<h1>Add member</h1>
View
Next, add a view in the members/views.py file, name the new view add:
members/views.py:
from django.http import HttpResponse
from django.template import loader
from .models import Members
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
def add(request):
template = loader.get_template('add.html')
return HttpResponse(template.render({}, request))
URLs
Add a path() function in the members/urls.py file, that points the url 127.0.0.1:8000/members/add/ to the right
location:
members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
]
In the browser, click the "Add member" link and the result should look like this:
More URLs
Did you notice the action attribute in the HTML form? The action attribute specifies where to send the form data, in
this case the form data will be sent to addrecord/, so we must add a path() function in the members/urls.py file that
points to the right view:
members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
path('add/addrecord/', views.addrecord, name='addrecord'),
]
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
def add(request):
template = loader.get_template('add.html')
return HttpResponse(template.render({}, request))
def addrecord(request):
x = request.POST['first']
y = request.POST['last']
member = Members(firstname=x, lastname=y)
member.save()
return HttpResponseRedirect(reverse('index'))
Changes that are made in the views.py file:
Line 1: import HttpResponseRedirect
Line 3: import reverse
The addrecord view does the following:
● Gets the first name and last name with the request.POST statement.
● Adds a new record in the members table.
● Redirects the user back to the index view.
Try to add a new record and see how it works:
If you press the submit button, the members table should have been updated:
Django Delete Record
Deleting Records
To delete a record we do not need a new template, but we need to make some changes to the members template.
Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each
record in a new table column.
The "delete" link will also contain the ID of each record.
Modify Template
Add a "delete" column in the members template:
members/templates/index.html:
<h1>Members</h1>
<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
<td><a href="delete/{{ x.id }}">delete</a></td>
</tr>
{% endfor %}
</table>
<p>
<a href="add/">Add member</a>
</p>
The result will look like this:
URLs
The "delete" link in the HTML table points to 127.0.0.1:8000/members/delete/ so we will add a path() function in the
members/urls.py file, that points the url to the right location, with the ID as a parameter:
members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
path('add/addrecord/', views.addrecord, name='addrecord'),
path('delete/<int:id>', views.delete, name='delete'),
]
def add(request):
template = loader.get_template('add.html')
return HttpResponse(template.render({}, request))
def addrecord(request):
x = request.POST['first']
y = request.POST['last']
member = Members(firstname=x, lastname=y)
member.save()
return HttpResponseRedirect(reverse('index'))
Modify Template
Start by adding a link for each member in the table:
members/templates/index.html:
<h1>Members</h1>
<table border="1">
{% for x in mymembers %}
<tr>
<td><a href="update/{{ x.id }}">{{ x.id }}</a></td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
<td><a href="delete/{{ x.id }}">delete</a>
</tr>
{% endfor %}
</table>
<p>
<a href="add/">Add member</a>
</p>
The link goes to a view called update with the ID of the current member.
The result will look like this:
View
Next, add the update view in the members/views.py file:
members/views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Members
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers
}
return HttpResponse(template.render(context, request))
def add(request):
template = loader.get_template('add.html')
return HttpResponse(template.render({}, request))
def addrecord(request):
first = request.POST['first']
last = request.POST['last']
member = Members(firstname=first, lastname=last)
member.save()
return HttpResponseRedirect(reverse('index'))
def delete(request, id):
member = Members.objects.get(id=id)
member.delete()
return HttpResponseRedirect(reverse('index'))
New Template
Add a new template in the templates folder, named update.html:
members/templates/update.html:
<h1>Update member</h1>
URLs
Add a path() function in the members/urls.py file, that points the url 127.0.0.1:8000/members/update/ to the right
location, with the ID as a parameter:
members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
path('add/addrecord/', views.addrecord, name='addrecord'),
path('delete/<int:id>', views.delete, name='delete'),
path('update/<int:id>', views.update, name='update'),
]
In the browser, click the ID of the member you want to change and the result should look like this:
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
path('add/addrecord/', views.addrecord, name='addrecord'),
path('delete/<int:id>', views.delete, name='delete'),
path('update/<int:id>', views.update, name='update'),
path('update/updaterecord/<int:id>', views.updaterecord, name='updaterecord'),
]
def index(request):
mymembers = Members.objects.all().values()
template = loader.get_template('index.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
def add(request):
template = loader.get_template('add.html')
return HttpResponse(template.render({}, request))
def addrecord(request):
x = request.POST['first']
y = request.POST['last']
member = Members(firstname=x, lastname=y)
member.save()
return HttpResponseRedirect(reverse('index'))
If you press the submit button, the members table should have been updated:
Refernces - https://www.w3schools.com/django/django_models.php
https://www.w3schools.com/django/django_add_members.php
https://www.w3schools.com/django/django_add_template.php
https://www.w3schools.com/django/django_add_record.php
https://www.w3schools.com/django/django_delete_record.php
https://www.w3schools.com/django/django_update_record.php
Activity 8
Aim: Create Django application validates user credentials on login pages
Learning outcome: Able to understand basic user authentication and authorization .
Duration: 4 hour
List of Hardware/Software requirements:
1. Django
2. Python
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()
If you have the Django admin installed, you can also create users interactively.
Creating superusers¶
Create superusers using the createsuperuser command:
$ python manage.py createsuperuser --username=joe [email protected]
You will be prompted for a password. After you enter one, the user will be created immediately. If you leave off the --
username or --email options, it will prompt you for those values.
Changing passwords¶
Django does not store raw (clear text) passwords on the user model, but only a hash (see documentation of how passwords
are managed for full details). Because of this, do not attempt to manipulate the password attribute of the user directly. This is
why a helper function is used when creating a user.
To change a user’s password, you have several options:
manage.py changepassword *username* offers a method of changing a user’s password from the command line. It
prompts you to change the password of a given user which you must enter twice. If they both match, the new password will
be changed immediately. If you do not supply a user, the command will attempt to change the password whose username
matches the current system user.
You can also change a password programmatically, using set_password():
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='john')
>>> u.set_password('new password')
>>> u.save()
If you have the Django admin installed, you can also change user’s passwords on the authentication system’s admin pages.
Django also provides views and forms that may be used to allow users to change their own passwords.
Changing a user’s password will log out all their sessions. See Session invalidation on password change for details.
Authenticating users¶
authenticate(request=None, **credentials)¶
Use authenticate() to verify a set of credentials. It takes credentials as keyword arguments, username and password for the
default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a
backend. If the credentials aren’t valid for any backend or if a backend raises PermissionDenied, it returns None. For
example:
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# A backend authenticated the credentials
else:
# No backend authenticated the credentials
request is an optional HttpRequest which is passed on the authenticate() method of the authentication backends.
Note
This is a low level way to authenticate a set of credentials; for example, it’s used by the RemoteUserMiddleware. Unless
you are writing your own authentication system, you probably won’t use this. Rather if you’re looking for a way to login a
user, use the LoginView.
Permissions and Authorization¶
Django comes with a built-in permissions system. It provides a way to assign permissions to specific users and groups of
users.
It’s used by the Django admin site, but you’re welcome to use it in your own code.
The Django admin site uses permissions as follows:
● Access to view objects is limited to users with the “view” or “change” permission for that type of object.
● Access to view the “add” form and add an object is limited to users with the “add” permission for that type of
object.
● Access to view the change list, view the “change” form and change an object is limited to users with the
“change” permission for that type of object.
● Access to delete an object is limited to users with the “delete” permission for that type of object.
Permissions can be set not only per type of object, but also per specific object instance. By using the
has_view_permission(), has_add_permission(), has_change_permission() and has_delete_permission() methods
provided by the ModelAdmin class, it is possible to customize permissions for different object instances of the same type.
User objects have two many-to-many fields: groups and user_permissions. User objects can access their related objects in
the same way as any other Django model:
myuser.groups.set([group_list])
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
myuser.user_permissions.set([permission_list])
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
Default permissions¶
When django.contrib.auth is listed in your INSTALLED_APPS setting, it will ensure that four default permissions – add,
change, delete, and view – are created for each Django model defined in one of your installed applications.
These permissions will be created when you run manage.py migrate; the first time you run migrate after adding
django.contrib.auth to INSTALLED_APPS, the default permissions will be created for all previously-installed models, as
well as for any new models being installed at that time. Afterward, it will create default permissions for new models each
time you run manage.py migrate (the function that creates permissions is connected to the post_migrate signal).
Assuming you have an application with an app_label foo and a model named Bar, to test for basic permissions you should
use:
● add: user.has_perm('foo.add_bar')
● change: user.has_perm('foo.change_bar')
● delete: user.has_perm('foo.delete_bar')
● view: user.has_perm('foo.view_bar')
The Permission model is rarely accessed directly.
Groups¶
django.contrib.auth.models.Group models are a generic way of categorizing users so you can apply permissions, or some
other label, to those users. A user can belong to any number of groups.
A user in a group automatically has the permissions granted to that group. For example, if the group Site editors has the
permission can_edit_home_page, any user in that group will have that permission.
Beyond permissions, groups are a convenient way to categorize users to give them some label, or extended functionality. For
example, you could create a group 'Special users', and you could write code that could, say, give them access to a members-
only portion of your site, or send them members-only email messages.
Programmatically creating permissions¶
While custom permissions can be defined within a model’s Meta class, you can also create permissions directly. For
example, you can create the can_publish permission for a BlogPost model in myapp:
from myapp.models import BlogPost
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(
codename='can_publish',
name='Can Publish Posts',
content_type=content_type,
)
The permission can then be assigned to a User via its user_permissions attribute or to a Group via its permissions
attribute.
Proxy models need their own content type
If you want to create permissions for a proxy model, pass for_concrete_model=False to
ContentTypeManager.get_for_model() to get the appropriate ContentType:
content_type = ContentType.objects.get_for_model(BlogPostProxy, for_concrete_model=False)
Permission caching¶
The ModelBackend caches permissions on the user object after the first time they need to be fetched for a permissions
check. This is typically fine for the request-response cycle since permissions aren’t typically checked immediately after they
are added (in the admin, for example). If you are adding permissions and checking them immediately afterward, in a test or
view for example, the easiest solution is to re-fetch the user from the database. For example:
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.get(
codename='change_blogpost',
content_type=content_type,
)
user.user_permissions.add(permission)
...
Proxy models¶
Proxy models work exactly the same way as concrete models. Permissions are created using the own content type of the
proxy model. Proxy models don’t inherit the permissions of the concrete model they subclass:
class Person(models.Model):
class Meta:
permissions = [('can_eat_pizzas', 'Can eat pizzas')]
class Student(Person):
class Meta:
proxy = True
permissions = [('can_deliver_pizzas', 'Can deliver pizzas')]
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
def logout_view(request):
logout(request)
# Redirect to a success page.
Note that logout() doesn’t throw any errors if the user wasn’t logged in.
When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This
is to prevent another person from using the same web browser to log in and have access to the previous user’s session data.
If you want to put anything into the session that will be available to the user immediately after logging out, do that after
calling django.contrib.auth.logout().
References: https://docs.djangoproject.com/en/4.0/topics/auth/
https://docs.djangoproject.com/en/4.0/topics/auth/default/
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication
Activity 9
Aim: Create admin panel using Django using AJAX.
Learning outcome: Able to understand basic how to implement AJAX .
Duration: 4 hour
List of Hardware/Software requirements:
1. Django
2. Python
Introduction
This tutorial explains how to carry out an ajax request in the Django web framework. We will create a
simple post-liking app as a part of the example.
Glossary
● Project Initialization
● Create models
● Create views
● Write URLs
● Carry out a request with Jquery Ajax.
● Register models to admin and add some posts.
Implementation:
1. Initiate the Django Project – Here I am assuming that you are done with Django Installation.
● To Create a Django Project execute:
$ django-admin startproject django_example
● After creating a project we need to create a Django app. To create an app say “post” execute
the following:
$ cd django_example
$ python manage.py startapp post
● Go to django_example/settings.py add the post-app
Output/Results snippet:
Reference : https://www.geeksforgeeks.org/handling-ajax-request-in-django/
https://github.com/saganshul/django_tutorials/tree/master/django_ajax/django_example
Activity 10
Aim: Perform crud operations in Django app using AJAX at single page
Learning outcome: Able to understand basic computer network technology.
Duration: 5 hour
List of Hardware/Software requirements:
1. Django
2. JQuery
3. Python
Let’s see the example of Python Django Ajax CRUD Operations. Ajax is a way of making web development
more dynamic. Using Ajax we can load data from the server without reloading the web pages. AJAX stands
for Asynchronous Javascript and XML.
In this tutorial, you’ll learn how to do CRUD operations using Django, Ajax Form Submission and JSON.
We will be using the Class Based Views Functions. CRUD operation is the most basic operation that we
perform on databases. CRUD stands for Create, Read, Update, Delete. We’ll take an example of a User
Management System where we will add, update and delete users and its detail.
Basic Configuration
In this tutorial, we are going to use JQuery for implementing Ajax requests.
base.html
{% load static %}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Title{% endblock title %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
{% block stylesheet %}{% endblock stylesheet %}
</head>
<body>
<main>
{% block content %}
{% endblock content %}
</main>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
{% block javascript %}
{% endblock javascript%}
</body>
</html>
# models.py
class CrudUser(models.Model):
name = models.CharField(max_length=30, blank=True)
address = models.CharField(max_length=100, blank=True)
age = models.IntegerField(blank=True, null=True)
# Views.py
class CrudView(ListView):
model = CrudUser
template_name = 'crud_ajax/crud.html'
context_object_name = 'users'
# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
]
Crud.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container">
<h1>Django Ajax CRUD</h1>
<div class="row">
<div class="col-md-4 ">
<h3>ADD USER</h3>
<form id="addUser" action="">
<div class="form-group">
<input class="form-control" type="text" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control" type="text" name="address" placeholder="Address" required>
</div>
<div class="form-group">
<input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age"
required>
</div>
<button class="btn btn-primary form-control" type="submit">SUBMIT</button>
</form>
</div>
<div class="col-md-8">
<h3>USERS</h3>
<table id="userTable" class="table table-striped">
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="3">Age</th>
</tr>
{% if users %}
{% for user in users %}
<tr id="user-{{user.id}}">
<td class="userName userData" name="name">{{user.name}}</td>
<td class="userAddress userData" name="address">{{user.address}}</td>
<td class="userAge userData" name="age">{{user.age}}</td>
<td align="center">
<button class="btn btn-success form-control" onClick="editUser({{user.id}})" data-
toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control"
onClick="deleteUser({{user.id}})">DELETE</button>
</td>
</tr>
{% endfor %}
{% else %}
No Users
{% endif %}
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-
hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update User</h4>
</div>
<form id="updateUser" action="">
<div class="modal-body">
<input class="form-control" id="form-id" type="hidden" name="formId"/>
<label for="name">Name</label>
<input class="form-control" id="form-name" type="text" name="formName"/>
<label for="address">Address</label>
<input class="form-control" id="form-address" type="text" name="formAddress"/>
<label for="age">Age</label>
<input class="form-control" id="form-age" type="number" name="formAge" min=10 max=100/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
{% endblock javascript %}
In our HTML code, you will find the Add User form and modal for update user details, we will be going to
use it later. So far our template should look like this:
Now it’s time to go with Ajax Calls.
# Views.py
class CreateCrudUser(View):
def get(self, request):
name1 = request.GET.get('name', None)
address1 = request.GET.get('address', None)
age1 = request.GET.get('age', None)
obj = CrudUser.objects.create(
name = name1,
address = address1,
age = age1
)
user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age}
data = {
'user': user
}
return JsonResponse(data)
Note– We are not rendering the template, we are just returning JsonResponse and we are also using Ajax Get
Method.
We are getting the form data using request.GET.get(address, None), address is the form’s input name
attribute. Then we are creating a user and sending back the user which we have created so to display it on the
web page.
# urls.py
from django.urls import path
from crud_ajax import views
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
]
Now let again add javascript and jquery ajax request in Crud.html which we have created while listing the
users
Crud.html
...
{% block javascript %}
<script>
// Create Django Ajax Call
$("form#addUser").submit(function() {
var nameInput = $('input[name="name"]').val().trim();
var addressInput = $('input[name="address"]').val().trim();
var ageInput = $('input[name="age"]').val().trim();
if (nameInput && addressInput && ageInput) {
// Create Ajax Call
$.ajax({
url: '{% url "crud_ajax_create" %}',
data: {
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
appendToUsrTable(data.user);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#addUser').trigger("reset");
return false;
});
function appendToUsrTable(user) {
$("#userTable > tbody:last-child").append(`
<tr id="user-${user.id}">
<td class="userName" name="name">${user.name}</td>
'<td class="userAddress" name="address">${user.address}</td>
'<td class="userAge" name="age">${user.age}</td>
'<td align="center">
<button class="btn btn-success form-control" onClick="editUser(${user.id})" data-
toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control"
onClick="deleteUser(${user.id})">DELETE</button>
</td>
</tr>
`);
}
</script>
{% endblock javascript %}
The working of the above JQuery is like that when you submit the form id=’addUser’, It will take the values
of the input fields and ajax call will be gone to the server.
$.ajax({
url: '{% url "crud_ajax_create" %}',
data: {
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
appendToUsrTable(data.user);
}
}
});
Let us understand what the above ajax request commanding to the browser.
URL – where resource is located:
url: '/ajax/crud/create/',
Data Type – Type of Data we want in return:
dataType: 'json',
# Views.py
class UpdateCrudUser(View):
def get(self, request):
id1 = request.GET.get('id', None)
name1 = request.GET.get('name', None)
address1 = request.GET.get('address', None)
age1 = request.GET.get('age', None)
obj = CrudUser.objects.get(id=id1)
obj.name = name1
obj.address = address1
obj.age = age1
obj.save()
user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age}
data = {
'user': user
}
return JsonResponse(data)# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'),
]
crud.html
...
// Create Django Ajax Call
$("form#updateUser").submit(function() {
var idInput = $('input[name="formId"]').val().trim();
var nameInput = $('input[name="formName"]').val().trim();
var addressInput = $('input[name="formAddress"]').val().trim();
var ageInput = $('input[name="formAge"]').val().trim();
if (nameInput && addressInput && ageInput) {
// Create Ajax Call
$.ajax({
url: '{% url "crud_ajax_update" %}',
data: {
'id': idInput,
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
updateToUserTabel(data.user);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#updateUser').trigger("reset");
$('#myModal').modal('hide');
return false;
});
class DeleteCrudUser(View):
def get(self, request):
id1 = request.GET.get('id', None)
CrudUser.objects.get(id=id1).delete()
data = {
'deleted': True
}
return JsonResponse(data)# urls.py
urlpatterns = [
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'),
path('ajax/crud/delete/', views.DeleteCrudUser.as_view(), name='crud_ajax_delete'),
]
Crud.html
// Delete Django Ajax Call
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this user?");
if (action != false) {
$.ajax({
url: '{% url "crud_ajax_delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
}
}
});
}
}
Deleting User using Ajax Django is one of the easiest ways. In ajax request, we are sending an id of the
object which we want to delete to view. In View, delete query is executed and deleted flag is sent in
Response. In success, we directly write the jQuery function to remove the section which we want to remove
from the table using id dynamically.
Output/Results snippet:
Reference: https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
Github link for Django AJAX CRUD- https://github.com/studygyaan/How-To-Execute-CRUD-Using-
Django-Ajax-and-JSON
Activity 11
Aim: Create Django application which sends email to any recipient.
Learning outcome: Learn how to send email using Django.
Duration: 3 hour
List of Hardware/Software requirements:
1. Python
2. Django
3. VS Code
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = #sender's email-id
EMAIL_HOST_PASSWORD = #password associated with above email-id
#In the above code, EMAIL_HOST_USER = ‘[email protected]’ and EMAIL_HOST_PASSWORD =
‘xyz123abc@’ are the lines where you need to add the sender’s mail id and password. [email protected]
and xyz123abc@ are just examples.
Step 3: Now to use this in our application, move to views.py and add these lines at the top section as below.
Step 4: Generally, emails are sent to the users who signup right? So, in the signup view function, add these
lines.
In above code ,
#subject refers to the email subject.
#message refers to the email message, the body of the email.
#email_from refers to the sender’s details.This takes the EMAIL_HOST_USER from settings.py file, where
you added those lines of code earlier.
#recipient_list is the list of recipients to whom the mail has to be sent that is, whoever registers to your
application they receive the email.
#send_mail is an inbuilt Django function that takes subject, message, email_from, and recipient’s list as
arguments, this is responsible to send emails.
Output/Results snippet:
Now, register any user to your application, and they will receive mail from the email account you had
mentioned.
Reference: https://www.geeksforgeeks.org/setup-sending-email-in-django-project/
Annexure
1. Installing Notepad++
a. Download Notepad++. You can download Notepad++ by clicking here. Click on the
"Download" button, and the program will begin downloading to your computer.
Click here Download 32-bit x86
Click here Download 64-bit x64
b. Double-click on the downloaded installer to start the installation. It is a wizard-driven
installation.
c. Let’s start…………….
Select language.
d. Click next and follow instructions