0% found this document useful (0 votes)
4 views

Notes - Advanced Python Sem VI CBCS NEP 1.0

The document outlines the syllabus for an Advanced Python course, detailing its structure, teaching scheme, and key topics including Exception Handling and Object-Oriented Programming. It provides a comprehensive overview of exception handling in Python, including built-in and user-defined exceptions, the raise statement, and the assert statement. Additionally, the document introduces Django and its components related to web development, emphasizing the importance of robust programming practices.

Uploaded by

sankettippe9766
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Notes - Advanced Python Sem VI CBCS NEP 1.0

The document outlines the syllabus for an Advanced Python course, detailing its structure, teaching scheme, and key topics including Exception Handling and Object-Oriented Programming. It provides a comprehensive overview of exception handling in Python, including built-in and user-defined exceptions, the raise statement, and the assert statement. Additionally, the document introduces Django and its components related to web development, emphasizing the importance of robust programming practices.

Uploaded by

sankettippe9766
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Advanced Python

B.Sc. III Sem. VI (Computer Science Paper XVI)


Course Code – DSE-F24

Author: Asst. Prof. N. S. Kulkarni


Email – [email protected]
Cell – 9890966539 / 9096194081
B.Sc. Part – III Computer Science (Optional) (Semester – VI)
Computer Science Paper –XVI
Course Code: DSE-F24 Course Title: Advanced Python
Teaching Scheme: Theory – 03 Lect. / Week
Credits: 02 Total Marks: 50

Unit – 1: Exception Handling and Object-Oriented Programming Concepts (18 Hrs.)

Exception Handling: Exception, Exception Handling, except clause, Try, finally clause, User
Defined Exceptions.
Object Oriented Programming Concepts: Class and object, Attributes, Inheritance,
Overloading, Overriding, and Data hiding.

Unit – 2: Introduction to Django (18 Hrs.)

Introduction to Django: Concepts of Web Page, Django Project & server configuration, MVT
Design Pattern, View, Template, URL Mapping, Django Forms, Form Validation, Database
connectivity, Django Middleware, Session & cookies.
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Unit – I Exception Handling

1.1 Exception Handling


1.1.1 Exception
An exception is a runtime error which can be handled by the programmer. That
means if the programmer can guess an error in the program and he can do something to
eliminate the harm caused by that error, then it is called an ‘exception’. If the programmer
cannot do anything in case of an error, then it is called an ‘error’ and not an exception.
All exceptions are represented as classes in Python. The exceptions which are already
available in Python are called ‘built-in’ exceptions. The base class for all built-in exceptions is
‘BaseException’ class. From ‘BaseException’ class, the sub class ‘Exception’ is derived. From
Exception class, the sub classes ‘StandardError’ and ‘Warning’ are derived.
All errors/exceptions are defined as sub classes of StandardError. An error should be
compulsorily handled otherwise the program will not execute. Similarly, all warnings are
derived as sub classes of ‘Warning’ class. A warning represents a caution and even though it
is not handled, the program will execute. So, warnings can be neglected but errors cannot be
neglected.
Just like the exceptions which are already available in Python language, a
programmer can also create his own exceptions, called ‘user-defined’ exceptions. When the
programmer wants to create his own exception class, he should derive his class from
Exception class and not from ‘BaseException’ class.

1.1.2 Exception Handling

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 1


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

The purpose of handling errors is to make the program robust that is strong. A robust
program does not terminate in the middle. Also, when there is an error in the program, it will
display an appropriate message to the user and continue exception. Designing such
programs is needed in any software development. For this purpose, the programmer should
handle the errors. When the errors can be handled, they are called exceptions. To handle
exceptions, the programmer should perform the following three steps:

Step 1: Observe the statements in his program where there may be a possibility if
exceptions. Such statements should be written inside a ‘try’ block. A try block looks like as
follows:
try:
statements
The greatness of try block is that even if some exception arises inside it, the program will not
be terminated. When PVM understands that there is an exception, it jumps into an ‘except’
block.

Step 2: The programmer should write the 'except' block where he should display the
exception details to the user. This helps the user to understand that there is some error in
the program. The programmer should also display a message regarding what can be done to
avoid this error. Except block looks like as follows:
except exceptionname:
statements #these statements form handler
The statements written inside an except block are called 'handlers' since they handle the
situation when the exception occurs.
Step 3: Lastly, the programmer should perform clean up actions like closing the files and
terminating any other processes which are running. The programmer should write this code
in the finally block. Finally block looks like as follows:
finally:
statements
The specialty of finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not. This ensures that all the opened files are
properly closed and all the running processes are properly terminated. So, the data in the
files will not be corrupted and the user is at the safe-side.

Syntax:
try:
# Code block
# These statements are those which can probably have some error

except:
# This block is optional.
# If the try block encounters an exception, this block will handle it.

else:
# If there is no exception, this code block will be executed by the Python interpreter

finally:
# Python interpreter will always execute this code.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 2


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Python Defined Exceptions List


Sr. Exception Description of the Exception
1 Exception All exceptions of Python have a base class.
2 StopIteration If the next() method returns null for an iterator, this exception is
raised.
3 SystemExit The sys.exit() procedure raises this value.
4 StandardError Excluding the StopIteration and SystemExit, this is the base class for all
Python built-in exceptions.
5 ArithmeticError All mathematical computation errors belong to this base class.
6 OverflowError This exception is raised when a computation surpasses the numeric
data type's maximum limit.
7 FloatingPointError If a floating-point operation fails, this exception is raised.
8 ZeroDivisionError For all numeric data types, its value is raised whenever a number is
attempted to be divided by zero.
9 AssertionError If the Assert statement fails, this exception is raised.
10 AttributeError This exception is raised if a variable reference or assigning a value fails.
11 EOFError When the endpoint of the file is approached, and the interpreter didn't
get any input value by raw_input() or input() functions, this exception
is raised.
12 ImportError This exception is raised if using the import keyword to import a
module fails.
13 KeyboardInterrupt If the user interrupts the execution of a program, generally by hitting
Ctrl+C, this exception is raised.
14 LookupError LookupErrorBase is the base class for all search errors.
15 IndexError This exception is raised when the index attempted to be accessed is
not found.
16 KeyError When the given key is not found in the dictionary to be found in, this
exception is raised.
17 NameError This exception is raised when a variable isn't located in either local or
global namespace.
18 UnboundLocalError This exception is raised when we try to access a local variable inside a
function, and the variable has not been assigned any value.
19 EnvironmentError All exceptions that arise beyond the Python environment have this
base class.
20 IOError If an input or output action fails, like when using the print command or
the open() function to access a file that does not exist, this exception is
raised.
22 SyntaxError This exception is raised whenever a syntax error occurs in our
program.
23 IndentationError This exception was raised when we made an improper indentation.
24 SystemExit This exception is raised when the sys.exit() method is used to
terminate the Python interpreter. The parser exits if the situation is
not addressed within the code.
25 TypeError This exception is raised whenever a data type-incompatible action or
function is tried to be executed.
26 ValueError This exception is raised if the parameters for a built-in method for a
particular data type are of the correct type but have been given the
wrong values.
27 RuntimeError This exception is raised when an error that occurred during the
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 3
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

program's execution cannot be classified.


28 NotImplementedError If an abstract function that the user must define in an inherited class is
not defined, this exception is raised.
1.1.3 Except clause
The except block is useful to catch an exception that is raised in the try block. When there is
an exception in the try block, then only the except block is executed. It is written in various
formats.
1. to catch the exception which is raised in the try block, we can write except block with the
exception class name as:
except ExceptionClass:
2. we can catch the exception as an object that contains some description about the
exception.
except ExceptionClass as obj:
3. To catch multiple exceptions, we can write catch blocks. The other way is to use a single
except block and write all the exceptions as a tuple inside parentheses as:
except (ExceptionClass1, ExceptionClass2):
4. To catch any type of exception where we are not bothered about which type of exception
it is, we can write except block without mentioning any ExceptionClass name, which will be a
common block for handling all types of exceptions as:
except:
5. We can also specify a except block for handling many exceptions by providing a tuple of
exception classes, as below
except (ValueError,ZeroDivisionError):
This block will handle both types of Exceptions.

Example:
#a function to find total and average of list elements
def avg(list):
tot=0
for x in list:
tot+=x
avg=tot/len(list)
return tot,avg

try:
t,a=avg([1,2,3,4,5,’a’])
print(‘Total={}, Average={}’.format(t,a))
except TypeError:
print(‘Type Error, Please provide numbers’)
except ZeroDivisionError:
print(‘ZeroDivisionError, Please do not give empty list’)

1.1.4 User Defined Exceptions


Like the built-in exceptions of Python, the programmer can also create his own exceptions
which are called ‘User-Defined Exceptions’ or ‘Custom Exceptions’. We know Python offers
many exceptions which will raise in different contexts. For example, when a number is
divided by 0, the ZeroDivisionError is raised.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 4


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

But there may be some situations where none of the exceptions in Python are useful
for the programmer. In that case, the programmer has to create his own exception and raise
it. For this purpose, he has to follow these steps –
1. Since all exceptions are classes, the programmer is supposed to create his own exception
as a class. Also, he should make his class as a sub class of the in-built ‘Exception’ class.
class MyException(Exception):
def __init__(self,arg):
self.msg=arg
Here, ‘MyException’ class is the sub class of Exception class. this class has a constructor
where variable ‘msg’ is defined. Theis ‘msg’ receives a message passed from outside through
‘arg’.
2. The programmer can write his code; maybe it represents a group of statements or a
function. when the programmer suspects the possibility if exception, he should raise his
exception using ‘raise’ statement as :
raise MyException(“message”)
Here, raise statement is raising MyException class object that contains the given “message”.
3. The programmer can insert the code inside a try block and catch the exception using
except block as :
try:
code
except MyException as me:
prinit(me)
Here, the object ‘me’ contains the message given in the raise statement.

Example:
class MyException(Exception):
def __init__(self,arg):
self.msg=arg

amt=500
try:
if(amt<1000):
raise MyException(“Low account balance”)
except MyException as obj:
print(obj)

1.1.4.1 The raise statement


The raise statement in Python is used to explicitly generate an exception during the
execution of a program. It is a mechanism that allows developers to signal that an error or
exceptional condition has occurred, interrupting the normal flow of the program. This is
particularly useful for enforcing constraints, debugging, and ensuring the program adheres
to its expected behavior. Raising an exception stops the normal execution flow and looks for
a suitable except block to handle it. The raise statement in Python is a powerful tool for
handling and signaling errors in a controlled manner. It enables developers to maintain
robust and reliable code by ensuring that unexpected or invalid conditions are properly
managed. With proper use of built-in and custom exceptions, raise can significantly enhance
the readability and maintainability of a Python program.
The general syntax of the raise statement is:
raise [ExceptionType]([message])
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 5
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• ExceptionType: Specifies the type of exception to raise (e.g., ValueError, TypeError,


ZeroDivisionError, etc.). This is optional, and if not provided, the current exception in
the program will be re-raised.
• message: A custom string providing additional information about the exception. This
is optional.

Uses of raise Statement

1. Raising Built-in Exceptions


Python provides several built-in exception classes like ValueError, TypeError, and
ZeroDivisionError. These can be raised explicitly using the raise statement to indicate specific
errors.
def check_positive(number):
if number < 0:
raise ValueError("Number must be positive.")
return number

try:
check_positive(-5)
except ValueError as e:
print(e)

2. Custom Error Messages


When raising an exception, you can include a custom error message to provide more details
about the error.
def divide(a, b):
if b == 0:
raise ZeroDivisionError("You cannot divide by zero.")
return a / b

try:
divide(10, 0)
except ZeroDivisionError as e:
print(e)

3. Creating Custom Exceptions


In Python, you can define your own exceptions by subclassing the built-in Exception class.
This makes it easier to categorize and handle specific types of errors.
class InvalidAgeError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)

def validate_age(age):
if age < 18:
raise InvalidAgeError("Age must be at least 18.")
print("Valid age.")

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 6


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

try:
validate_age(16)
except InvalidAgeError as e:
print(f"Error: {e}")
1.1.5 The assert Statement
The assert statement is useful to ensure that a given condition is True. If it is not true, it
raises AssertionError. The syntax is as follow:
assert condition,message
If the condition is False, then the exception by the name AssertionError is raised along with
the message written in the assert statement. If message is not given in the assert statement
and the condition is False, then also AssertionError is raised without message.
Example:
try:
x=int(input(“Enter a number between 5 and 10:”))
assert x<5 and x>10
print(“The entered number”,x)
except AssertionError as obj:
print(“Condition is not fullfilled”)

1.2 Object Oriented Programming Concepts


Object Oriented Programming (OOP) is a computer programming model that
organizes software design around data, or objects, rather than functions and logic. An object
can be defined as a data field that has unique attributes and behavior.
OOP focuses on the objects that developers want to manipulate rather than the logic
required to manipulate them. This approach to programming is well-suited for programs that
are large, complex and actively updated or maintained. This includes programs for
manufacturing and design, as well as mobile applications; for example, OOP can be used for
manufacturing system simulation software.
The organization of an object-oriented program also makes the method beneficial to
collaborative development, where projects are divided into groups. Additional benefits of
OOP include code reusability, scalability and efficiency.
The structure, or building blocks, of object-oriented programming include the following:
• Classes are user-defined data types that act as the blueprint for individual objects,
attributes and methods.
• Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity. When class is defined initially,
the description is the only object that is defined.
• Methods are functions that are defined inside a class that describe the behaviors of
an object. Each method contained in class definitions starts with a reference to an
instance object. Additionally, the subroutines contained in an object are called
instance methods. Programmers use methods for reusability or keeping functionality
encapsulated inside one object at a time.
• Attributes are defined in the class template and represent the state of an object.
Objects will have data stored in the attributes field. Class attributes belong to the
class itself.

What are the main principles of OOP?


Object-oriented programming is based on the following principles:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 7


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• Encapsulation. This principle states that all important information is contained inside
an object and only select information is exposed. The implementation and state of
each object are privately held inside a defined class. Other objects do not have access
to this class or the authority to make changes. They are only able to call a list of
public functions or methods. This characteristic of data hiding provides greater
program security and avoids unintended data corruption.
• Abstraction. Objects only reveal internal mechanisms that are relevant for the use of
other objects, hiding any unnecessary implementation code. The derived class can
have its functionality extended. This concept can help developers more easily make
additional changes or additions over time.
• Inheritance. Classes can reuse code from other classes. Relationships and subclasses
between objects can be assigned, enabling developers to reuse common logic while
still maintaining a unique hierarchy. This property of OOP forces a more thorough
data analysis, reduces development time and ensures a higher level of accuracy.
• Polymorphism. Objects are designed to share behaviors and they can take on more
than one form. The program will determine which meaning or usage is necessary for
each execution of that object from a parent class, reducing the need to duplicate
code. A child class is then created, which extends the functionality of the parent class.
Polymorphism allows different types of objects to pass through the same interface.

1.2.1 Class and object


The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain
an attribute and method, i.e., an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
The object is an entity that has a state and behavior associated with it. It may be any real-
world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer
or any single string is an object. The number 12 is an object, the string “Hello, world” is an
object, a list is an object that can hold other objects, and so on. You’ve been using objects all
along and may not even realize it.
An object consists of:
• State: It is represented by the attributes of an object. It also reflects the properties of
an object.
• Behavior: It is represented by the methods of an object. It also reflects the response
of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code. When we define a class, it needs to create an object to allocate the
memory. Consider the following example.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 8


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1
object will allocate memory for these values. We will learn more about class and object in
the next tutorial.
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.

1.2.1.1 The ‘self’


SELF represents the instance of class. This handy keyword allows you to access
variables, attributes, and methods of a defined class in Python. The self parameter doesn’t
have to be named “self,” as you can call it by any other name. However, the self parameter
must always be the first parameter of any class function, regardless of the name chosen. self
represents the instance of the class. By using the “self” we can access the attributes and methods of
the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to
instance attributes. Python decided to do methods in a way that makes the instance to
which the method belongs be passed automatically, but not received automatically: the first
parameter of methods is the instance the method is called on
Example:
class check:
def __init__(self):
print("Address of self = ",id(self))

obj = check()
print("Address of class object = ",id(obj))

1.2.1.2 Constructor
Constructors are generally used for instantiating an object. The task of constructors is
to initialize (assign values) to the data members of the class when an object of the class is
created. In Python the __init__() method is called the constructor and is always called when
an object is created. Syntax of constructor declaration :

def __init__(self):
# body of the constructor

Types of constructors:
1. default constructor: The default constructor is a simple constructor which
doesn’t accept any arguments. Its definition has only one argument which is a
reference to the instance being constructed.
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 9
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2. parameterized constructor: constructor with parameters is known as


parameterized constructor. The parameterized constructor takes its first
argument as a reference to the instance being constructed known as self and
the rest of the arguments are provided by the programmer.

Example constructor:
class Addition:
first = 0
second = 0
answer = 0

# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s

def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))

def calculate(self):
self.answer = self.first + self.second

# creating object of the class this will invoke parameterized constructor


obj1 = Addition(1000, 2000)
# creating second object of same class
obj2 = Addition(10, 20)
# perform Addition on obj1
obj1.calculate()
# perform Addition on obj2
obj2.calculate()
# display result of obj1
obj1.display()
# display result of obj2
obj2.display()

1.2.1.3 Destructor
Destructors are called when an object gets destroyed. In Python, destructors are not
needed as much as in C++ because Python has a garbage collector that handles memory
management automatically. The __del__() method is a known as a destructor method in
Python. It is called when all references to the object have been deleted i.e. when an object is
garbage collected.

Syntax of destructor declaration :

def __del__(self):
# body of destructor

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 10


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

1.2.2 Attributes
As an object-oriented language, Python provides two scopes for attributes: class attributes
and instance attributes. Python class attributes are variables of a class that are shared
between all of its instances. They differ from instance attributes in that instance attributes
are owned by one specific instance of the class and are not shared between instances.
While the instance attribute in Python has exactly the same characteristics and definition as
other object-oriented languages, the class attribute is often mistakenly considered to be the
exact equivalent of the static attribute in Java or C++. Class attributes in Python and static
attributes in Java or C++ have a lot in common, but they have several behavioral differences
that I will highlight in this article.
• An instance attribute is a Python variable belonging to one, and only one, object. This
variable is only accessible in the scope of this object, and it’s defined inside the
constructor function, __init__(self,..) of the class.
• A class attribute is a Python variable that belongs to a class rather than a particular
object. It’s shared between all the objects of this class and is defined outside the
constructor function, __init__(self,...), of the class.
The below ExampleClass is a basic Python class with two attributes: class_attr and
instance_attr.
class ExampleClass(object):
class_attr = 0

def __init__(self, instance_attr):


self.instance_attr = instance_attr

instance_attr is an instance attribute defined inside the constructor.


class_attr is a class attribute defined outside the constructor.

The instance_attr is only accessible from the scope of an object. The class attribute
(class_attr) is accessible as both a property of the class and as a property of objects, as it’s
shared between all of them.

if __name__ == '__main__':
foo = ExampleClass(1)
bar = ExampleClass(2)
# print the instance attribute of the object foo
print (foo.istance_attr)
#print the instance attribute of the object var
print (bar.instance_attr)
#print the class attribute of the class ExampleClass as a property of the class itself
print (ExampleClass.class_attr)
#print the classattribute of the class as a proporty of the objects foo,bar
print (bar.class_attr)
print (foo.class_attr)
# try to print instance attribute as a class property
print (ExampleClass.instance_attr)

#AttributeError: type object 'ExampleClass' has no attribute 'instance_attr'

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 11


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Notice that the class attribute can be accessed as a class property and as an instance
property, however, accessing an instance attribute as a class property raises an
AttributeError.

1.2.3 Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch. In inheritance, the child class acquires the properties and
can access all the data members and functions defined in the parent class. A child class can
also provide its specific implementation to the functions of the parent class. In this section of
the tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.
Python Inheritance
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak

1.2.3.1 Types of Inheritance


In Python, inheritance is a mechanism where a new class derives properties and behavior
(methods) from an existing class. It allows the creation of a new class that is based on an
existing class, enabling code reusability and making it easier to manage complex systems.
There are several types of inheritance in Python, depending on how the classes are related
and how the inheritance hierarchy is structured.

Types of Inheritance in Python:


1. Single Inheritance
In single inheritance, a derived class inherits from a single base class. It is the simplest form
of inheritance.
# Base class

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 12


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

class Animal:
def sound(self):
print("Animal makes a sound")

# Derived class
class Dog(Animal):
def bark(self):
print("Dog barks")
# Creating an object of the derived class
dog = Dog()
dog.sound() # Inherited method
dog.bark() # Method in the derived class

2. Multiple Inheritances
In multiple inheritance, a derived class inherits from more than one base class. This allows
the derived class to inherit features from multiple classes.
# Base classes
class Animal:
def sound(self):
print("Animal makes a sound")

class Dog:
def bark(self):
print("Dog barks")

# Derived class
class Hybrid(Dog, Animal):
def run(self):
print("Hybrid can run")

# Creating an object of the derived class


hybrid = Hybrid()
hybrid.sound() # Inherited from Animal
hybrid.bark() # Inherited from Dog
hybrid.run() # Method in Hybrid class

In this example:
• The class Hybrid inherits from both Dog and Animal, allowing it to access methods
from both base classes.
The Method Resolution Order (MRO):
When using multiple inheritance, Python follows the C3 Linearization (C3 superclass
linearization) algorithm to determine the order in which classes are checked for methods.
The mro() method can be used to view the MRO.
print(Hybrid.mro())

3. Multilevel Inheritance
In multilevel inheritance, a derived class becomes the base class for another derived class.
This creates a chain of inheritance where each class inherits from its predecessor.
# Base class
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 13
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

class Animal:
def sound(self):
print("Animal makes a sound")

# Intermediate class
class Mammal(Animal):
def has_hair(self):
print("Mammals have hair")

# Derived class
class Dog(Mammal):
def bark(self):
print("Dog barks")

# Creating an object of the derived class


dog = Dog()
dog.sound() # Inherited from Animal
dog.has_hair() # Inherited from Mammal
dog.bark() # Defined in Dog

4. Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherit from a single base class. Each
derived class can have its own behavior while still sharing common functionality from the
base class.
# Base class
class Animal:
def sound(self):
print("Animal makes a sound")

# Derived class 1
class Dog(Animal):
def bark(self):
print("Dog barks")

# Derived class 2
class Cat(Animal):
def meow(self):
print("Cat meows")

# Creating objects of the derived classes


dog = Dog()
dog.sound() # Inherited from Animal
dog.bark()

cat = Cat()
cat.sound() # Inherited from Animal
cat.meow()

5. Hybrid Inheritance
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 14
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Hybrid inheritance is a combination of two or more types of inheritance. For example, it


could involve a mix of single, multiple, or multilevel inheritance.
# Base class 1
class Animal:
def sound(self):
print("Animal makes a sound")

# Base class 2
class Mammal:
def has_hair(self):
print("Mammals have hair")

# Derived class 1
class Dog(Animal, Mammal):
def bark(self):
print("Dog barks")

# Derived class 2
class Bat(Mammal, Animal):
def fly(self):
print("Bat can fly")

# Creating objects of the derived classes


dog = Dog()
dog.sound() # Inherited from Animal
dog.has_hair() # Inherited from Mammal
dog.bark()

bat = Bat()
bat.has_hair() # Inherited from Mammal
bat.sound() # Inherited from Animal
bat.fly()

1.2.3.2 Super Function: The super() function is commonly used in inheritance to call
methods from a parent class. It ensures that the next method in the method resolution order
is called, which is particularly important in multiple and multilevel inheritance.
Example:
class Animal:
def speak(self):
print("Animal makes a sound")

class Dog(Animal):
def speak(self):
super().speak() # Calls Animal's speak method
print("Dog barks")

dog = Dog()
dog.speak() # Output: Animal makes a sound \n Dog barks

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 15


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

1.2.4 Overloading
Function overloading is the feature when multiple functions have the same name, but the
number of parameters in the functions varies. Python does not support function overloading
as in other languages, and the functional parameters do not have a data type. Suppose we
want to use the feature of functional overloading. In that case, we can set the default values
of parameters in the method as None, which won’t give an error if that specific value is not
passed as an argument while calling the function.
The problem with method overloading in Python is that we may overload the methods but
can only use the latest defined method.
def product(a, b):
p=a*b
print(p)

# Second product method Takes three argument and print their product

def product(a, b, c):


p = a * b*c
print(p)

# Uncommenting the below line shows an error


# product(4, 5)

# This line will call the second product method


product(4, 5, 5)

In the above code, we have defined two product methods we can only use the second
product method, as python does not support method overloading. We may define many
methods of the same name and different arguments, but we can only use the latest defined
method. Calling the other method will produce an error. Like here calling product(4,5) will
produce an error as the latest defined product method takes three arguments.

1.2.5 Overriding
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class method is
needed in the child class.
Consider the following example to perform method overriding in python.

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 16
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

1.2.6 Data hiding


This is achieved in Python using the concept of encapsulation, which helps in
maintaining control over how the internal attributes and methods of a class are accessed and
modified. Data hiding is a concept which underlines the hiding of data or information from
the user. It is one of the key aspects of Object-Oriented programming strategies. It includes
object details such as data members, internal work. Data hiding excludes full data entry to
class members and defends object integrity by preventing unintended changes. Data hiding
also minimizes system complexity for increase robustness by limiting interdependencies
between software requirements. Data hiding is also known as information hiding. In class, if
we declare the data members as private so that no other class can access the data members,
then it is a process of hiding data.
The Python document introduces Data Hiding as isolating the user from a part of
program implementation. Some objects in the module are kept internal, unseen, and
unreachable to the user. Modules in the program are easy enough to understand how to use
the application, but the client cannot know how the application functions. Thus, data hiding
imparts security, along with discarding dependency. Data hiding in Python is the technique
to defend access to specific users in the application. Python is applied in every technical area
and has a user-friendly syntax and vast libraries. Data hiding in Python is performed using the
(__) double underscore prefix for private and (_) single underscore for protected members.
This makes the class members non-public and isolated from the other classes.
class Solution:
__privateCounter = 0

def sum(self):
self.__privateCounter += 1
print(self.__privateCounter)

count = Solution()
count.sum()
count.sum()

# Here we have accessed the private data member through class name.
print(count._Solution__privateCounter)

Advantages of Data Hiding:


1. It helps to prevent damage or misuse of volatile data by hiding it from the public.
2. The class objects are disconnected from the irrelevant data.
3. It isolates objects as the basic concept of OOP.
4. It increases the security against hackers that are unable to access important data.

Disadvantages of Data Hiding:


1. It enables programmers to write lengthy code to hide important data from common
clients.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 17


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2. The linkage between the visible and invisible data makes the objects work faster, but
data hiding prevents this linkage.

1.2.6 Data Encapsulation


Data encapsulation is a fundamental concept in object-oriented programming (OOP) that
involves bundling data (attributes) and the methods (functions) that operate on that data
into a single unit, typically a class. Encapsulation ensures that the internal representation of
an object is hidden from the outside, allowing controlled access through well-defined
interfaces.
Key Features of Data Encapsulation
1. Combines Data and Methods: Encapsulation groups related data and operations
(methods) together in a class.
2. Controlled Access: Provides mechanisms to control access to the data using access
modifiers.
3. Information Hiding: Protects sensitive data from unintended access and modification.
4. Improved Security and Maintenance: Encapsulation enforces a clear boundary
between the internal implementation of a class and the external interface.

Example:
class Employee:
def __init__(self, name, salary):
self.__name = name # Private attribute
self.__salary = salary # Private attribute

# Getter method for name


def get_name(self):
return self.__name

# Setter method for name


def set_name(self, name):
self.__name = name

# Getter method for salary


def get_salary(self):
return self.__salary

# Setter method for salary


def set_salary(self, salary):
if salary > 0:
self.__salary = salary
else:
raise ValueError("Salary must be positive.")
# Usage
emp = Employee("John Doe", 50000)
# Access data using getter methods
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 18
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

print(emp.get_name()) # John Doe


print(emp.get_salary()) # 50000
# Modify data using setter methods
emp.set_name("Jane Smith")
emp.set_salary(60000)
print(emp.get_name()) # Jane Smith
print(emp.get_salary()) # 60000
UNIT II
2.1 Concepts of Web
2.1.1 What is Internet?
The Internet is essentially a global network of computing resources. You can think of the
Internet as a physical collection of routers and circuits as a set of shared resources.
Some common definitions given in the past include −
• A network of networks based on the TCP/IP communications protocol.
• A community of people who use and develop those networks.

2.1.2 Internet-Based Services


• Email − A fast, easy, and inexpensive way to communicate with other Internet
users around the world.
• Telnet − Allows a user to log into a remote computer as though it were a local
system.
• FTP − Allows a user to transfer virtually every kind of file that can be stored on a
computer from one Internet-connected computer to another.
• UseNet news − A distributed bulletin board that offers a combination news and
discussion service on thousands of topics.
• World Wide Web (WWW) − A hypertext interface to Internet information
resources.

2.1.3 What is WWW?


WWW stands for World Wide Web. A technical definition of the World Wide Web is − All
the resources and users on the Internet that are using the Hypertext Transfer Protocol
(HTTP).
A broader definition comes from the organization that Web inventor Tim Berners-Lee
helped found, the World Wide Web Consortium (W3C): The World Wide Web is the
universe of network-accessible information, an embodiment of human knowledge.
In simple terms, The World Wide Web is a way of exchanging information between
computers on the Internet, tying them together into a vast collection of interactive
multimedia resources.

2.1.4 What is HTTP?

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 19


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

HTTP stands for Hypertext Transfer Protocol. This is the protocol being used to transfer
hypertext documents that makes the World Wide Web possible. A standard web address
such as Yahoo.com is called a URL and here the prefix http indicates its protocol

2.1.5 What is URL?


URL stands for Uniform Resource Locator, and is used to specify addresses on the World
Wide Web. A URL is the fundamental network identification for any resource connected
to the web (e.g., hypertext pages, images, and sound files).
A URL will have the following format −
protocol://hostname/other_information
The protocol specifies how information is transferred from a link. The protocol used for
web resources is HyperText Transfer Protocol (HTTP). Other protocols compatible with
most web browsers include FTP, telnet, newsgroups, and Gopher.
The protocol is followed by a colon, two slashes, and then the domain name. The domain
name is the computer on which the resource is located.
Links to particular files or subdirectories may be further specified after the domain name.
The directory names are separated by single forward slashes.

2.1.6 What is Website?


website is a collection of various pages written in HTML markup language. This is a
location on the web where people can find tutorials on latest technologies. Similarly,
there are millions of websites available on the web.
Each page available on the website is called a web page and first page of any website is
called home page for that site.

2.1.7 What is Web Server?


Every Website sits on a computer known as a Web server. This server is always
connected to the internet. Every Web server that is connected to the Internet is given a
unique address made up of a series of four numbers between 0 and 256 separated by
periods. For example, 68.178.157.132 or 68.122.35.127.
When you register a Web address, also known as a domain name, such as
tutorialspoint.com you have to specify the IP address of the Web server that will host the
site.

2.1.8 What is Web Browser?


Web Browsers are software installed on your PC. To access the Web, you need a web
browser, such as Netscape Navigator, Microsoft Internet Explorer or Mozilla Firefox.
Currently you must be using any sort of Web browser while you are navigating through
my site tutorialspoint.com. On the Web, when you navigate through pages of
information this is commonly known as browsing or surfing.

2.1.9 What is HTML?

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 20


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

HTML stands for Hyper Text Markup Language. This is the language in which we write
web pages for any Website. Even the page you are reading right now is written in HTML.
This is a subset of Standard Generalized Mark-Up Language (SGML) for electronic
publishing, the specific standard used for the World Wide Web.

2.1.10 What is Hyperlink?


A hyperlink or simply a link is a selectable element in an electronic document that serves
as an access point to other electronic resources. Typically, you click the hyperlink to
access the linked resource. Familiar hyperlinks include buttons, icons, image maps, and
clickable text links.
2.1.11 What is a Webpage
A web page is a single hypertext document available on World Wide Web (WWW). It is
composed of HTML elements and displayed on the user's browser such as Mozilla,
Firefox, Chrome, etc. It is also referred to as "Page."
A webpage is a document written in HTML and can be viewed on any web browser. It is
contained within the web server, which can be accessed by entering the URL for that web
page, and once it is loaded, it appears on the user's web browser. Each webpage is linked
with a unique URL; hence two pages cannot have the same URL. A webpage may contain
text, links for other pages, graphics, videos, etc. Moreover, it is mainly used to provide
information to the user in text, images, etc. A webpage is a part of a website; it means a
website contains different web pages.

2.1.12 How does a Web Page Work?


A simple web page is created using HTML, which is a markup language. However, we can
also use CSS and JavaScript to add more functionalities and make it more attractive.
It is created using HTML, hence containing different markup tags that specify how the
data should be formatted on screen.
The webpage is contained within the webserver. To load this webpage, a client sends the
request to the server, and generally, the browser is known as the client, which can
request the page on the internet.
The web browser requests the page on the internet. Once it is responded to by the
server, the browser interprets the markup tags and displays them on the user's screen in
the correct format.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 21


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

The browser sends the request for a page or a file via an HTTP request. The HTTP is
the Hypertext Transfer Protocol, a network protocol that allows transferring hypermedia
documents over the internet between a browser and server.
Once the request reaches the server, the HTTP server accepts the request, finds the
requested page, and sends it back to the browser through the HTTP response. If a server
is unable to find the requested page, it returns a 404 response.

2.2 Introduction to Django


Django is a Python-based web application framework that is free and open source. A
framework is simply a collection of modules that facilitate development. They're
grouped together and allow you to build apps or websites from scratch rather than
starting from scratch. "Rapid development and clean, pragmatic design" are key
benefits of Django. When installed on a web server, the Django web framework can
assist developers in quickly creating a feature-rich, secure, and scalable web
frontend.
For example, developers should not create their login screens or login processing.
There are far too many possibilities for things to go wrong. Frameworks take care of
this for you and handle all the tricky cases.
Django is a web development framework that assists in building and maintaining
quality web applications. Django helps eliminate repetitive tasks making the
development process an easy and time saving experience. This tutorial gives a
complete understanding of Django.
Django is a high-level Python web framework that allows the rapid development of
secure and maintainable websites. It is free and open source. It is used for full-stack
app development and server development. Django is suitable for the backend as well
as the frontend. It is a collection of Python libraries that allows us to develop useful
web apps ideal for backend and frontend purposes.
Django was developed in 2003 by the web developers of Lawrence Journal World
Newspaper, Arian Holovaty, and Simon Willison. Adrian Holovaty named this web
framework after a famous jazz guitarist, Django Reinhardt. It was publicly released in

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 22


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

July 2005 under the BSD license. Currently, DSF (Django Software Foundation) is
maintaining its development and release cycle.
Django is a web development framework for building websites and web applications
using Python. It provides a set of tools and features that make it easier to create web
applications quickly and efficiently. Django handles common web development tasks
like database management, URL routing, form handling, and user authentication,
allowing developers to focus on building the unique features of application instead of
reinventing the wheel. It follows the "Don't Repeat Yourself" (DRY) principle,
promoting code reuse and maintainability.

2.2.1 Features Of Django


➢ Rapid Development
Django was created with the goal of creating a framework that would allow
developers to build web applications in less time. The project implementation
phase takes a long time, but Django makes it happen quickly.
➢ Enhance Security
Django's security goes beyond its explicit security features: the extensive
experience and expertise of the Django user base bolster security efforts. You run
the risk of accidentally introducing a security vulnerability into your module if you
build your entire web app from scratch. You can be more confident that Django
packages will protect your data because they are widely used, open-source, and
well-reviewed by web developers.
➢ Versatile
Django is a versatile framework that can be used to create applications in a
variety of domains. Companies are now using Django to create a variety of
applications, such as content management systems, social networking sites, and
scientific computing platforms, among others.
➢ Open Source
Django is a web application framework that is free and open source. It is freely
available to the public. The source code is available for download from the public
repository. The total cost of developing an application is reduced by using open
source.
➢ Vast and Supported Community
The Django web framework has a large and dedicated user base, with many
talented Django developers donating their time and expertise to help develop,
improve, and patch the software foundation. Your application can benefit from
this commitment by utilizing the well-designed packages available to anyone
building with Django.

2.3 Django Project & Server configuration


2.3.1 Creating Django project
Step 1: Set Up a Virtual Environment (Recommended)

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 23


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

A virtual environment is a self-contained directory that contains all the necessary


dependencies for a project, which helps to avoid conflicts with other projects.
1. Install virtualenv (if it's not already installed):
pip install virtualenv
2. Create a new virtual environment for your project: Navigate to the folder
where you want to create your project and run:
virtualenv venv
or
python -m venv /path/to/new/virtual/environment
3. Activate the virtual environment:
o Windows:
venv\Scripts\activate
or
C:\> <venv>\Scripts\activate.bat
4. Once activated, your prompt will change to show the virtual environment's
name, indicating you're working inside it.

Step 2: Install Django


After activating the virtual environment, install Django using pip:
pip install django
To verify the installation, run:
python -m django --version
This should print the version of Django you installed.

Step 3: Create a Django Project


Now, you’re ready to create a new Django project. To create a new Django project,
use the django-admin startproject command followed by the name of your project.
For example:
django-admin startproject myproject
This will create a folder named myproject with the following structure:
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py
├── urls.py
├── asgi.py
└── wsgi.py
o manage.py: A command-line utility that helps manage your Django
project.
o myproject/settings.py: The settings/configuration for your Django
project.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 24


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

o myproject/urls.py: The URL routing for your project.


o myproject/wsgi.py: The WSGI entry point for deployment.
o myproject/asgi.py: The ASGI entry point for handling asynchronous
requests (Django 3.0+).

Navigate into your project directory:


cd myproject

Step 4: Run the Development Server


Django comes with a built-in development server, which is useful for development
and testing. To start the server, run:
python manage.py runserver
By default, this will start the server on http://127.0.0.1:8000/ (local development
server). You should see a message like:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Now, open your browser and go to http://127.0.0.1:8000/. You should see the
Django welcome page, which confirms that your project is set up and running.

Step 5: Create a Django App


A Django project can consist of multiple apps. Each app is a module that encapsulates
a specific functionality of the project (like a blog, forum, etc.). To create an app, run
the following command from your project directory:
python manage.py startapp myapp
This will create a folder named myapp with the following structure:
myapp/
├── migrations/
│ └── __init__.py
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
Each of these files serves a specific purpose:
• models.py: Defines the data models for your app.
• views.py: Defines the views (handlers for HTTP requests).
• admin.py: Registers models for the Django admin interface.
• apps.py: Contains configuration for the app.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 25


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• tests.py: For writing tests for your app.


• migrations/: Holds database migrations.

Step 6: Configure the App in the Project


To make Django aware of your new app, you need to add it to the INSTALLED_APPS
list in myproject/settings.py. Open settings.py and find the INSTALLED_APPS section.
Add your app's name (myapp) like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # Add this line
]

Step 7: Create Database Tables


Now that you’ve added an app and made some changes, you need to create the
database tables for the models (if any) you define in your app.
1. Run migrations:
python manage.py migrate
This will apply all migrations (including Django's built-in apps like authentication) to
create the necessary database tables.

Step 8: Create a Superuser (Admin User)


To access Django's admin interface, you'll need to create an admin user.
Run the following command:
python manage.py createsuperuser
You’ll be prompted to enter a username, email address, and password for the admin
user.
Step 9: Access the Admin Interface
Once the superuser is created, you can access the Django admin interface by
navigating to http://127.0.0.1:8000/admin/ in your browser. Log in with the
superuser credentials you just created.
Step 10: Modify Views and URLs
1. Define a simple view in myapp/views.py:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, world!")
2. Map the view to a URL by editing myapp/urls.py. If this file doesn't exist,
create it. Then, add the following:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 26


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

from django.urls import path


from . import views
urlpatterns = [
path('', views.home, name='home'),
]
3. Include the app's URLs in the project’s main urls.py. Open myproject/urls.py
and add an include statement for myapp URLs:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Include the URLs of 'myapp'
]
Now, when you visit http://127.0.0.1:8000/, you should see the "Hello, world!"
response from your app.

2.3.2 Other Configurations


1. Set up the Database
Django uses SQLite as the default database in development mode, but you can configure
a different database if required. To use SQLite, simply run migrations:
1. Run the migrations for the default database:
python manage.py migrate
2. For production environments, you might want to configure a more robust database
like PostgreSQL or MySQL.

Configure PostgreSQL or MySQL :


For PostgreSQL, you would need to install psycopg2:
pip install psycopg2
Then, update DATABASES in settings.py with the appropriate configuration.
For MySQL, install mysqlclient:
pip install mysqlclient
You’ll then need to configure your database in settings.py as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', # Or mysql
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432', # Or MySQL port
}
}

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 27


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2. Configure Static and Media Files


In production, you must configure the static and media files, but you can also do so for
development to make sure the server works smoothly.
a. Configure Static Files:
In your settings.py, add the paths for the static and media files:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
b. Configure Media Files:
For user-uploaded files:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

2.4 MVT Design Pattern


2.4.1 Model-View-Template (MVT)
The MVT (Model-View-Template) design pattern is a software architectural pattern
primarily used in web development frameworks, particularly in Django, a popular
Python-based web framework. It is quite similar to the MVC (Model-View-Controller)
pattern but with key differences in the way it structures the handling of user
interfaces and interactions. The MVT pattern helps separate the logic of an
application into different layers, which improves the scalability, maintainability, and
clarity of the codebase.
The Django framework adapts a MVT approach. It is a slight variation of the MVC
approach. The acronym MVT stands for Model, View and Template. Here too, the
Model is the data layer of the application. The View is in fact the layer that
undertakes the processing logic. The Template is the presentation layer.

• Model
The Model represents the data and the business logic of the application. It defines
the structure of the database (or data source) and handles the interaction with
the data layer. This includes tasks like fetching, updating, and deleting data. In
Django, the Model is typically implemented using Django’s ORM (Object-
Relational Mapping), where each model is a Python class that maps to a database
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 28
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

table. The Model is also responsible for enforcing data validation rules and
providing an abstraction for accessing data from the underlying storage system.
Each Django model creates a corresponding database table, with each model
attribute becoming a field in the table.
• View
The View represents the user interface (UI) in the application. It is responsible for
rendering the data to the user and receiving input. However, unlike the MVC
pattern, where the View also handles user interaction, in MVT, the View is
focused solely on presenting the data.
In Django, the View refers to Python functions (or classes) that handle HTTP
requests and return HTTP responses. These views can render templates, pass data
to templates, and implement the business logic associated with handling user
requests. The View's role is to respond to user actions and invoke the necessary
logic in the Model to fetch data or perform some computation. It processes
incoming requests, retrieves data from the model, applies transformations, and
passes it to the template. Views in Django are Python functions or classes.
• Template
The Template is Django’s implementation of the View layer. It is responsible for
rendering the HTML that is returned to the client’s browser. It is a text file that
can include HTML and template tags (placeholders) that are replaced with
dynamic data when the page is generated. Templates allow the application to
present dynamic content by embedding data passed from the View layer into the
HTML. Django’s templating system provides a way to use control structures like
loops and conditional statements, making the presentation of data flexible. While
templates handle the presentation logic, they do not manage how the data is
obtained or how business rules are applied. Their primary role is to create the
final HTML to send to the browser.
Django templates are HTML files with placeholders for dynamic content, which
are filled in by the Django Template Language (DTL).

The MVT design pattern (Model-View-Template) is a variant of the MVC pattern that
structures web applications by separating the business logic (Model), user interface
(Template), and the request-handling logic (View). While the specific names and roles
of components differ from the traditional MVC pattern, the overall goal is the same:
to ensure clean separation of concerns, leading to maintainable, scalable, and
testable applications. MVT is particularly associated with Django, though the
pattern's concepts can be applied to other web development frameworks as well.

2.4.2 How MVT Works in Django


1. Request Handling:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 29


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

A client sends a request (such as loading a web page) to the server. The URL
dispatcher (which maps URLs to Views) processes the request and calls the
corresponding View function or class.
2. View Processing:
The View retrieves necessary data from the Model, processes it, and prepares the
context for the Template. In the case of dynamic content, the View may interact
with the database using Django’s ORM models, fetch data, and pass that data to
the Template.
3. Template Rendering:
The Template, which contains placeholders, receives the context data from the
View. The Template processes the data and returns a final HTML page to the
client, which is rendered in the user’s browser.

2.4.3 Advantages of the MVT Pattern:


1. Separation of Concerns:
o MVT provides a clear separation between the business logic (Model), the user
interface (Template), and the control flow (View). This results in cleaner, more
maintainable code.
2. Scalability:
o As your application grows, the separation of responsibilities makes it easier to
add new features or modify existing ones. Each component (Model, View,
Template) can evolve independently as long as the interfaces between them
remain consistent.

3. Testability:
o Since the application is broken into distinct layers (Model, View, Template),
testing becomes more straightforward. For example, you can unit-test the
Model and View layers independently.
4. Reusability:
o Templates allow for the reuse of presentation logic, reducing redundancy in
code. Likewise, Models can be reused across different Views.

2.4.4 MVC v/s MVT


• In the MVC pattern, the View directly interacts with the Model to retrieve data, while
the Controller manages user input and updates the Model. The Controller then
updates the View.
• In the MVT pattern, the View in Django refers to the function that handles HTTP
requests and responds with an HTML page. The Template, not the View, is
responsible for rendering HTML content. The Template is more focused on the
presentation of the data, while the View in Django handles user input and
coordinates the interaction between the Model and the Template.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 30


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2.4.5 Components of Django Application


A Django application consists of the following components –
• The URL Dispatcher
Django’s URL dispatcher mechanism is equivalent to Controller in the MVC
architecture. The urls.py module in the Django project’s package folder acts as the
dispatcher. It defines the URL patterns. Each URL pattern is mapped with a view
function to be invoked when the client’s request URL is found to be matching with it.
The URL patterns defined in each app under the project are also included in it.
When the server receives a request in the form of client URL, the dispatcher matches
its pattern with the patterns available in the urls.py and routes the flow of the
application towards its associated view.
• The View Function
The View function reads the path parameters, query parameters and the body
parameters included in the client’s request. It uses this data to interact with the
models to perform CRUD operations, if required.
• The Model Class
A Model is a Python class. Django uses the attributes of the Model class to construct a
database table of a matching structure. Django’s Object Relational Mapper helps in
performing CRUD operations in an object oriented way instead of invoking SQL
queries.
The View uses the data from the client as well as the model and renders its response
in the form of a template.

• Template
A Template is a web page in which HTML script is interspersed with the code blocks of
Django Template Language.
Django’s template processor uses any context data received from the View is inserted
in these blocks so that a dynamic response is formulated. The View in turn returns
the response to the user.

2.5 View
In Django, a view is a Python function or class that takes an HTTP request and returns
an HTTP response. Views can render HTML templates, redirect to other pages, return
data in various formats (such as JSON), or even trigger complex logic. Views handle
the user interaction with your website by processing user requests and returning
appropriate responses.
In Django, the View is a crucial component of the MVT (Model-View-Template) design
pattern, responsible for handling HTTP requests, interacting with models, processing
the necessary data, and returning an HTTP response. Unlike the Model, this defines
the data and business logic, and the Template, which handles presentation, the View

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 31


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

acts as the controller in the traditional MVC (Model-View-Controller) design pattern.


It determines what content is displayed and how the application responds to user
actions.

2.5.1 Key Responsibilities of a View in Django:


1. Handling HTTP Requests:
o A View receives and processes incoming HTTP requests from the user
(typically through a browser or API request). Django’s URL routing system
maps specific URLs to views, so when a request is made to a specific URL, the
corresponding view is executed.
2. Interacting with Models (Business Logic):
o Views interact with the Model to retrieve or modify data. For example, a view
may query a database to fetch specific records, create or update data, or
perform other business logic.
3. Processing Data and Logic:
o Views can perform various operations based on the request. This may include
validating form submissions, processing user input, or making decisions about
what data needs to be displayed or what actions to take.
4. Returning an HTTP Response:
o After processing the request, a View generates an HTTP response. This
response can be:
▪ An HTML page, rendered from a template.
▪ A redirect to another URL.
▪ A JSON response for APIs or AJAX calls.
▪ An XML response or other formats, depending on the application’s
needs.
o Django provides various response classes like HttpResponse, JsonResponse,
HttpResponseRedirect, etc., to manage different types of responses.

2.5.2 Types of Views


Django supports two main ways to define views: function-based views (FBVs) and
class-based views (CBVs). Both have their own strengths and use cases.
2.5.2.1 Function-Based Views (FBVs):
Function-based views are Python functions that take an HTTP request object as input
and return an HTTP response object. They are the simplest and most explicit way to
define views in Django.
Syntax: A function-based view looks like this:

from django.http import HttpResponse


from django.shortcuts import render
def my_view(request):
# Logic for handling the request

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 32


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

return HttpResponse("Hello, World!")

o request: The HTTP request object that contains metadata about the incoming
request (headers, user info, etc.).
o HttpResponse: A class that returns an HTTP response. You can also use
render() to return HTML pages rendered with templates.

• Advantages of FBVs:
o Simple and easy to understand.
o Explicit flow of control, making them a good choice for smaller applications or
simple views.
o Offers complete control over the request-response cycle.

• Limitations of FBVs:
o Can become repetitive and cumbersome for complex applications with many
views.
o Lack the built-in reusable behavior found in class-based views.

• Example: A simple function-based view


1. Create a view: In your Django app (let's call it myapp), go to myapp/views.py
and define a simple view.
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, world!")
In this example:
• home(request) is the view function.
• The request parameter represents the HTTP request received from the
browser.
• The function returns an HttpResponse with the message "Hello, world!".

2. Map the view to a URL: Django uses a URL dispatcher to map URLs to view
functions. To associate the home view with a URL, you need to configure it in
the urls.py file of your app. If you don’t already have a urls.py in your app,
create one in the myapp directory. Inside myapp/urls.py, define the URL
pattern for the view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
• path('', views.home) means that when a user accesses the root URL (/), the
home view will be called.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 33


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• name='home' is an optional name you can give to the URL, useful for reverse
URL resolution in templates.

3. Include the app URLs in the main urls.py: In the main urls.py of the project
(usually found in the myproject directory), include the URLs from myapp.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Include the URLs of 'myapp'
]
4. Run the server: Now, when you visit http://127.0.0.1:8000/, you should see
the text "Hello, world!" in your browser.

2.5.2.2 Class-Based Views (CBVs):


Class-based views are defined as Python classes that inherit from Django's View class
or one of its subclasses. These views are more abstract and promote reusability
through inheritance and mixins.
Syntax: A basic class-based view looks like this:
from django.http import HttpResponse
from django.views import View
class MyView(View):
def get(self, request):
return HttpResponse("Hello, World!")

• Advantages of CBVs:
o Promotes reuse of common behavior using mixins and base classes.
o Easier to extend and maintain for complex views, as you can break logic into
multiple methods (e.g., get, post, put).
o Django provides built-in generic class-based views like ListView, DetailView,
CreateView, UpdateView, and DeleteView that automatically handle common
tasks like displaying a list of objects or managing forms.
• Limitations of CBVs:
o More abstract and can be harder to understand for beginners.
o Requires understanding of object-oriented programming (OOP) concepts like
inheritance and mixins.

• Example: A simple class-based view


1. Create a class-based view: In myapp/views.py, create a new class-based view
using Django's View class.
from django.http import HttpResponse

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 34


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

from django.views import View


class HomeView(View):
def get(self, request):
return HttpResponse("Hello, world from a class-based view!")
o The HomeView class inherits from django.views.View, which is the base class
for all views.
o The get method is responsible for handling HTTP GET requests. You can also
define methods for handling POST, PUT, DELETE, etc.

2. Map the class-based view to a URL: To associate the class-based view with a
URL, you need to use as_view() when defining the URL pattern. This is
necessary to instantiate the class and returns a callable view.
In myapp/urls.py:
from django.urls import path
from .views import HomeView

urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
o HomeView.as_view() creates an instance of HomeView and returns it as a
callable view that can be used by the URL dispatcher.

3. Run the server: Now, when you visit http://127.0.0.1:8000/, you will see the
message "Hello, world from a class-based view!" in your browser.

2.5.3 How Views Work in Django:


1. URL Routing:
Django uses URL patterns to map URLs to views. In the urls.py file, you define URL
patterns using the path() or re_path() functions, associating each URL with a specific
view function or class.
Example:
from django.urls import path
from . import views

urlpatterns = [
path('hello/', views.my_view, name='hello'),
]
In this case, when a user visits /hello/, the my_view function will handle the request.
2. View Processing:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 35


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

The view takes the incoming HTTP request, processes it, and typically interacts with
the Model to fetch or modify data. The view may also involve validating user input,
applying business logic, or performing additional tasks.
3. Template Rendering (Optional):
If the view needs to return HTML, it will typically render a Template (which is an
HTML file with dynamic placeholders) using the render() function.
Example:
from django.shortcuts import render
def my_view(request):
context = {'message': 'Hello, World!'}
return render(request, 'my_template.html', context)
4. Returning the Response:
The view then generates and returns an appropriate HTTP response. If it's a simple
page, the view will return an HttpResponse with rendered HTML. For API responses,
it might return JsonResponse.

2.5.4 Django’s Built-in Views and Generic Views:


Django provides many pre-built views for common tasks, such as displaying lists of
objects, handling form submissions, and managing user authentication. These views
can be extended to suit specific needs or used as-is for faster development.
Generic Views: Django offers generic views like ListView, DetailView, and
CreateView, which automate many tasks associated with displaying objects or
handling forms. Example of a ListView:
from django.views.generic import ListView
from .models import MyModel
class MyModelListView(ListView):
model = MyModel
template_name = 'mymodel_list.html'

2.6 Template
Django provides a convenient way to generate dynamic HTML pages by using its
template system. A template consists of static parts of the desired HTML output as
well as some special syntax describing how dynamic content will be inserted. In HTML
file, we can't write python code because the code is only interpreted by python
interpreter not the browser. We know that HTML is a static markup language, while
Python is a dynamic programming language. Django template engine is used to
separate the design from the python code and allows us to build dynamic web pages.
In Django, a template is a file that defines the structure and layout of the HTML
content that will be rendered by the server and sent to the browser. Templates are
used to separate the logic of your application (in views) from its presentation (the
HTML output).

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 36


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Django uses a powerful templating engine that allows you to embed dynamic data
(like variables, loops, and conditionals) within your HTML files. These templates are
typically stored in the templates directory of your application or project.
A Template in Django is an HTML file (with optional Django template language
embedded) that defines how the data should be presented. Templates are
responsible for rendering data into HTML, which is then sent as an HTTP response to
the client (browser). Django templates use a specialized template language that
allows for the dynamic insertion of variables and the use of logic like loops,
conditionals, and more.
2.6.1 Template Files:
Templates are typically written as .html files, but they can be named with other
extensions if needed (e.g., .txt, .xml). These files contain HTML markup with Django
Template Language (DTL) embedded within the HTML structure. A template will
generally consist of static HTML mixed with dynamic placeholders that are replaced
with actual data when the template is rendered. Example of a simple Django
template (home.html):
<html>
<body>
<h1>Welcome, {{ user.name }}!</h1>
<p>We have {{ product_count }} products in our store.</p>
</body>
</html>
In this example, {{ user.name }} and {{ product_count }} are placeholders that will be
replaced with actual values when the template is rendered.

2.6.2 Template Tags:


Django templates use template tags to add logic and control structures to the HTML.
Template tags are enclosed in curly braces and percent signs {% %}. These tags are
processed by Django’s template engine to perform tasks such as looping over data,
conditionally rendering parts of the template, or including other templates.
Common template tags include:
▪ {% if condition %} ... {% endif %}: Conditional rendering.
▪ {% for item in items %} ... {% endfor %}: Looping over a list.
▪ {% block blockname %} ... {% endblock %}: Defining a section that can be
overridden in child templates (used for template inheritance).
▪ {% include 'template_name.html' %}: Including another template file.
Example of using an if tag:
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 37


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2.6.3 Template Filters:


Template filters are used to modify the output of variables before rendering them.
Filters are applied to variables by using the pipe | symbol. These filters allow you to
format data, truncate strings, apply dates, etc.
Example:
<p>The price is ${{ product.price|floatformat:2 }}</p>
In this example, the floatformat:2 filter formats the price to 2 decimal places.

2.6.4 Template Inheritance:


One of the most powerful features of Django templates is template inheritance,
which allows you to define a base template with common structure and content that
can be reused across different pages in the application. By using the {% block %} and
{% extends %} tags, you can define blocks in a parent template that can be overridden
in child templates, avoiding code duplication.
Example of a base template (base.html):
<html>
<body>
<header>
<h1>My Website</h1>
<nav>...</nav>
</header>

<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
Example of a child template (home.html):
{% extends 'base.html' %}
{% block content %}
<h2>Welcome to the homepage!</h2>
<p>Some dynamic content here...</p>
{% endblock %}
In this setup, the child template (home.html) inherits the structure defined in the
base template (base.html), and only the content inside the {% block content %} will
be replaced.

2.6.5 Static Files and Media:


Django provides built-in support for static files (CSS, JavaScript, images, etc.) and
media files (uploaded by users). Static files are typically placed in a folder named

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 38


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

static, and media files are stored in a directory defined in the settings (e.g., media).
The {% static %} template tag is used to link to static files in templates.
Example:
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<img src="{% static 'images/logo.png' %}" alt="Logo">

2.6.6 Rendering Templates in Views:


In Django, templates are rendered in views using the render() function, which takes
the request, the template name, and a context dictionary (containing data that will
populate the template placeholders).
Example of rendering a template from a view:
from django.shortcuts import render
def home_view(request):
context = {'user': request.user, 'product_count': 100}
return render(request, 'home.html', context)
In this example:
▪ The render() function loads the home.html template.
▪ It passes a context dictionary with the data (user and product_count).
▪ The placeholders {{ user.name }} and {{ product_count }} in the template will
be replaced by the actual values from the context.

2.6.7 Template Context:


The context is a dictionary passed from the view to the template. It contains the
dynamic data that the template will use to replace placeholders. The context can
include any Python object, such as strings, integers, dictionaries, or even entire
model instances.
Example:
def product_detail_view(request, product_id):
product = Product.objects.get(id=product_id)
context = {'product': product}
return render(request, 'product_detail.html', context)
In this case, the template product_detail.html would have access to the product
object, and you could display the product's attributes like {{ product.name }} and {{
product.price }}.

2.6.8 Template Caching:


Django also supports template caching, which can significantly improve performance
by caching parts of the rendered templates. This is especially useful in cases where
certain sections of the template (like a header or footer) do not change often, but the
rest of the page is dynamic. You can use Django’s cache template tag or set the
cache using settings for views or blocks.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 39


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2.6.9 Advantages of Using Templates in Django:


1. Separation of Concerns:
Templates allow designers and developers to work separately. Designers can focus on
the HTML and the structure, while developers handle the dynamic content and logic
in the views and models.
2. Reusability:
Templates support inheritance and inclusion, which means common page structures
can be reused across the application, reducing duplication of code.
3. Security:
Django templates are secure by default. For example, automatic escaping of variables
prevents XSS (Cross-Site Scripting) attacks, making it safe to render user-generated
content directly in templates.
4. Separation of Business Logic:
Templates allow the separation of presentation logic from business logic, making it
easier to maintain and update the application. Complex operations are handled in
views or models, not within the templates.

In Django, a Template is a powerful tool for rendering dynamic content in the web
application. It is responsible for presenting data to the user in a structured and secure
manner. Django’s template system offers a range of features, such as template inheritance,
filtering, and tagging, which make it easy to manage and extend the presentation layer of
your application. By separating business logic and presentation logic, Django templates
improve maintainability, reusability, and security in web development.

2.7 URL Mapping


In Django, URL mapping is the mechanism that associates URLs (Uniform Resource Locators)
with views—the Python functions or classes that handle the logic for each request. URL
mapping is an essential part of the Django framework, allowing developers to define clean,
human-readable URLs for different parts of their web applications. It plays a critical role in
defining the flow of user requests and how they are handled by the application.
In Django, URL mapping refers to the process of linking a URL (web address) to a specific
view in your Django application. When a user visits a URL in their browser, Django uses the
URL dispatcher to match the requested URL to a corresponding view, which then processes
the request and returns an appropriate response.
Django uses a URL configuration system called URLconf to map URLs to views. URLconf is
simply a Python module (usually a urls.py file) that contains a mapping between the URL
patterns and the views that should handle them. The core of URL mapping is defined in
the urls.py files. The view is linked to a URL pattern via the URLconf.

2.7.1 URL Mapping Process in Django


The process of URL mapping in Django typically follows these steps:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 40


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

1. Request URL: The user requests a specific URL in their browser (e.g.,
http://www.example.com/blog/).
2. Django URL Resolver: Django's URL resolver examines the incoming URL and tries to
find a matching pattern in the URL configuration.
3. Matching URL Pattern: If a URL pattern is found that matches the request URL, the
corresponding view is invoked to handle the request.
4. Response: The view generates a response (e.g., an HTML page, JSON data, etc.),
which is then sent back to the user's browser.

2.7.2 Anatomy of URL Mapping in Django


1. The urls.py File
In Django, URL patterns are typically defined in a Python module named urls.py. Each
URL pattern is defined as a Python list or tuple, where each entry corresponds to a
specific URL pattern and the view that handles it.
Example:
# myapp/urls.py
from django.urls import path
from . import views # Import views from the current app
urlpatterns = [
path('home/', views.home_view, name='home'),
# Maps URL 'home/' to 'home_view' function
path('about/', views.about_view, name='about'),
# Maps 'about/' to 'about_view' function
path('blog/<int:post_id>/', views.blog_detail, name='blog_detail'),
# URL pattern with dynamic variable
]

Explanation:
path(): The function path() is used to define URL patterns. It takes at least two
arguments:
o The first argument is the URL string (relative to the root of the site) that is
matched with the request URL.
o The second argument is the view that will be executed when the URL is
matched.
o Optionally, the third argument is a name for the URL pattern, which is
helpful for reverse URL lookup.
2. URL Pattern Matching
Django URL patterns use regular expressions (or simpler path converters in modern
versions) to match URL patterns. There are two main ways to define URL patterns in
Django:
a. Static URL Patterns (Fixed URLs)
These patterns match exactly with the requested URL.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 41


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Example:
urlpatterns = [
path('about/', views.about_view, name='about'), # Static URL pattern
]
Here, any request to http://www.example.com/about/ will be mapped to the
about_view function.

b. Dynamic URL Patterns (URL Variables)


Django allows for dynamic URL patterns where parts of the URL can be treated as
variables. These are useful when the URL depends on some value, such as an ID or a
username.
Example:
urlpatterns = [
path('blog/<int:post_id>/', views.blog_detail, name='blog_detail'),
]
Here:
• <int:post_id> is a path converter that specifies that Django should capture an
integer from the URL and pass it to the view as a variable.
• So, http://www.example.com/blog/42/ would map to views.blog_detail with
post_id set to 42.

c. Named URL Patterns (Reverse URL Resolution)


Django allows you to give names to your URL patterns, making it easier to reference
URLs in your templates or views. This feature is especially useful when URLs change,
as you can update the URL in one place without changing every reference to it.
Example:
# urls.py
urlpatterns = [
path('home/', views.home_view, name='home'),
]

# In the template or view:


<a href="{% url 'home' %}">Home</a>
This will create a link to /home/, and the URL will be resolved by Django dynamically.

3. Path Converters
Django's modern URL handling system supports path converters, which are simpler
alternatives to regular expressions for capturing dynamic parts of a URL.
The available path converters are:
• <int:variable_name>: Matches an integer and passes it as a Python integer to the
view.
• <str:variable_name>: Matches a string and passes it as a string.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 42


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• <slug:variable_name>: Matches a slug (letters, numbers, hyphens, and


underscores).
• <uuid:variable_name>: Matches a UUID and passes it as a UUID object.
• <path:variable_name>: Matches any string, including slashes (/).
Example using various converters:
urlpatterns = [
path('blog/<int:post_id>/', views.blog_detail),
# post_id is an integer
path('category/<slug:category_slug>/', views.category_view),
# category_slug is a string
path('file/<path:file_path>/', views.file_view),
# file_path is a path (could include slashes)
]
4. Include Other URLconf
Django allows you to organize your URL patterns across multiple modules by using
the include() function. This is especially useful for large projects with many apps.
Example:
# Project-level urls.py
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')), # Include blog app's URL patterns
path('shop/', include('shop.urls')), # Include shop app's URL patterns
]
In this case, Django will look for the urls.py file in the blog and shop apps and include
those URL patterns in the overall project.

2.7.3 Example of URL Mapping


# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_list, name='blog_list'), # Maps '/' to blog_list view
path('post/<int:id>/', views.blog_post, name='blog_post'), # Maps to individual
blog post
]

# blog/views.py
from django.shortcuts import render
from .models import BlogPost

def blog_list(request):
posts = BlogPost.objects.all()

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 43


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

return render(request, 'blog/blog_list.html', {'posts': posts})

def blog_post(request, id):


post = BlogPost.objects.get(id=id)
return render(request, 'blog/blog_post.html', {'post': post})

<!--blog_list.html-->
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li><a href="{% url 'blog_post' post.id %}">{{ post.title }}</a></li>
{% endfor %}
</ul>

2.8 Django Forms


Django provides a Form class which is used to create HTML forms. It describes a form
and how it works and appears. It is similar to the ModelForm class that creates a form
by using the Model, but it does not require the Model. Each field of the form class
map to the HTML form <input> element and each one is a class itself; it manages
form data and performs validation while submitting the form.
In Django, forms are an integral part of web development that handle the input and
validation of data submitted by users through HTML forms. Django provides a robust
framework to define, process, and validate forms efficiently.
Forms are used for taking input from the user in some manner and using that
information for logical operations on databases. For example, registering a user by
taking input such as his name, email, password, etc.
Django maps the fields defined in Django forms into HTML input fields. Django
handles three distinct parts of the work involved in forms:
• Preparing and restructuring data to make it ready for rendering.
• Creating HTML forms for the data.
• Receiving and processing submitted forms and data from the client.

Note that all types of work done by forms in Django can be done with advanced
HTML stuff, but Django makes it easier and efficient especially the validation part.
Once you get hold of forms in Django you will just forget about HTML forms.

Django forms are Python classes that represent HTML forms. They simplify the
creation and processing of forms by providing built-in features for rendering HTML,
validating data, and interacting with models.

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 44


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2.8.1 Form Class


The core of a Django form is a Python class that inherits from ‘forms.Form’. Each field
of the form is defined as a class attribute, representing an HTML input element.
Example:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, label='Your Name')
email = forms.EmailField(label='Your Email')
message = forms.CharField(widget=forms.Textarea, label='Your Message')
2.8.2 Fields
Fields represent the data the form will handle. Common field types include:
• CharField: Text input
• EmailField: Email input with validation
• IntegerField: Numeric input
• DateField: Date input with validation
• BooleanField: Checkbox input
Each field can have attributes like required, max_length, min_length, label, initial, and
help_text.

2.8.3 Widgets
Widgets determine the HTML representation of form fields. Django provides default widgets
for fields but allows customization.
Example:
message = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 30}))

2.8.4 Validation
Django validates form data through:
• Field-specific Validation: Built into each field (e.g., EmailField checks for valid email
format).
• Custom Validation Methods: Defined using the clean_<fieldname>() method.
Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 45
B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

• Form-wide Validation: Implemented in the clean() method for cross-field validation.


Example of custom validation:
def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('@example.com'):
raise forms.ValidationError("Email must end with @example.com")
return email

2.8.5 Workflow of Django Forms


1. Define the Form: Create a class in forms.py with desired fields.
2. Render the Form in Templates: Use Django’s template tags to display the form.
3. Process Form Data:
o Instantiate the form with POST data (form = ContactForm(request.POST)).
o Validate data using form.is_valid().
o Access cleaned data through form.cleaned_data.
4. Handle Form Submission: Process the valid data, save it to the database, or perform
other actions.

2.8.6 Model Forms


Django ModelForms provide a way to create forms directly linked to models, reducing
redundant code.
Example:
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'content', 'author']
Key Features:
• Automatically maps model fields to form fields.
• Includes model validation rules.

2.8.7 Rendering Django Forms in Templates


Use the {{ form.as_p }}, {{ form.as_table }}, or {{ form.as_ul }} methods for default rendering,
or customize the HTML structure.
Example:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 46


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

2.8.8 Example
1. forms.py:
python
CopyEdit
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)

2. views.py:
python
CopyEdit
from django.shortcuts import render
from .forms import ContactForm
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form data
print(form.cleaned_data)
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})

3. contact.html:
html
CopyEdit
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

2.9 Form Validation


Django provides built-in methods to validate form data automatically. Django forms
submit only if it contains CSRF tokens. It uses uses a clean and easy approach to
validate data. The is_valid() method is used to perform validation for each field of the
form, it is defined in Django Form class. It returns True if data is valid and place all
data into a cleaned_data attribute.
Form validation is the process of ensuring that data entered into a form meets
specific requirements before it is processed or saved. It is a critical aspect of web

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 47


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

development, as it ensures data integrity, prevents malicious input, and enhances the
user experience by guiding users to provide correct information.
Form validation verifies that:
• All required fields are filled.
• Input data matches the expected type (e.g., integers, emails).
• Data adheres to specific rules (e.g., a password's minimum length).
• Custom conditions or relationships between fields are satisfied.
In web development frameworks like Django, form validation is handled through
built-in methods and can be extended with custom validation logic.

2.9.1 Types of Form Validation


a) Client-Side Validation
Performed in the browser using HTML5 attributes (e.g., required, maxlength) or
JavaScript.
• Pros:
o Provides instant feedback to users.
o Reduces unnecessary server requests.
• Cons:
o Can be bypassed by disabling JavaScript or manipulating the DOM.
Example:
<form>
<input type="email" required>
<button type="submit">Submit</button>
</form>

b) Server-Side Validation
Performed on the server after the form is submitted.
• Pros:
o Ensures secure and reliable validation.
o Handles all data submitted, even if client-side validation is bypassed.
• Cons:
o Slightly slower as it requires a server round-trip.
Example in Django:
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField(max_length=100)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('@example.com'):

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 48


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

raise forms.ValidationError("Email must be from the @example.com


domain.")
return email

2.9.2 Validation Workflow in Django


1. Define the Form: Create a form class in forms.py with validation logic.
2. Receive Input: The form is populated with user input using request.POST or
request.GET.
3. Call is_valid(): This method:
a) Validates all fields.
b) Returns True if valid and False if any field fails.
4. Access Validated Data:
a) cleaned_data: Contains validated data.
b) errors: Contains details of validation errors.

2.9.3 Built-In Validation in Django


a) Field-Level Validation
Django fields have built-in validation. For instance:
CharField: Checks max_length and min_length.
EmailField: Validates email format.
IntegerField: Ensures input is an integer.

Example:
name = forms.CharField(max_length=50, required=True)

2.9.4 Validation Methods


1. clean_<fieldname>():
o Used for custom validation of a specific field.
Example:
def clean_username(self):
username = self.cleaned_data.get('username')
if len(username) < 5:
raise forms.ValidationError("Username must be at least 5 characters long.")
return username
2. clean():
o Used for cross-field validation or overall form validation.
Example:
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 49


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

if password != confirm_password:
raise forms.ValidationError("Passwords do not match.")

2.9.5 Custom Validation


a) Custom Validators
Validators are reusable validation functions. Django provides a validators module and
allows custom ones.
Example:
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError('%(value)s is not an even number', params={'value':
value})
Usage:
from django import forms
class NumberForm(forms.Form):
number = forms.IntegerField(validators=[validate_even])

b) Custom Error Messages


You can override default error messages for specific fields. Example:
email = forms.EmailField(error_messages={'required': 'Please enter your
email.'})

2.9.6 Validation Error Handling


a) form.errors
Stores errors if is_valid() returns False. Each field's errors are accessible via
form.errors['fieldname'].
b) b. Displaying Errors in Templates
Use the {{ form.errors }} variable or field-specific errors like {{ form.field.errors }}.
Example:
{% for error in form.email.errors %}
<p>{{ error }}</p>
{% endfor %}

2.9.7 Examples of Validation in Action


Example 1: A Login Form
class LoginForm(forms.Form):
username = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)

def clean_username(self):
username = self.cleaned_data.get('username')

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 50


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

if not username.isalnum():
raise forms.ValidationError("Username must be alphanumeric.")
return username
Example 2: Registration Form with Password Validation
class RegistrationForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)

def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')

if password != confirm_password:
raise forms.ValidationError("Passwords must match.")

2.10 Database connectivity


Django provides a robust and user-friendly framework for connecting to and interacting with
databases. It abstracts the complexities of database interactions through its Object-
Relational Mapping (ORM) system, enabling developers to work with database objects using
Python code instead of SQL.
The settings.py file contains all the project settings along with database connection details.
By default, Django works with SQLite, database and allows configuring for other databases as
well. Database connectivity requires all the connection details such as database name, user
credentials, hostname drive name etc. To connect with MySQL, django.db.backends.mysql
driver is used to establishing a connection between application and database. Let's see an
example. We need to provide all connection details in the settings file. The settings.py file of
our project contains the following code for the database. Django supports multiple relational
databases, such as:
• PostgreSQL
• MySQL
• SQLite (default)
• Oracle

2.10.1 Configuring Database Connectivity


a) Default SQLite Configuration
When you create a Django project, it uses SQLite by default. The configuration in
settings.py looks like this:
DATABASES = {
'default': {

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 51


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

b) Configuring a Different Database


To use other databases, update the DATABASES dictionary with the appropriate
settings.
Example for MySQL:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}

Example for PostgreSQL:


DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'database_name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}

2.10.2 Models and the ORM


a. Defining Models
In Django, models are defined as Python classes in the models.py file. Each model
represents a database table.
Example:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 52


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

def __str__(self):
return self.title

b. Migrating Models
Once models are defined, Django requires you to create and apply database migrations
to synchronize the models with the database schema.
1. Create Migrations:
python manage.py makemigrations
2. Apply Migrations:
python manage.py migrate

2.10.3 CRUD Operations with Django ORM


a. Creating Records
article = Article(title="First Article", content="This is the content of the first article.")
article.save()
b. Reading Records
# Get all articles
articles = Article.objects.all()
# Filter articles
filtered_articles = Article.objects.filter(title__icontains="first")
# Get a single article
single_article = Article.objects.get(id=1)
c. Updating Records
article = Article.objects.get(id=1)
article.title = "Updated Title"
article.save()
d. Deleting Records
article = Article.objects.get(id=1)
article.delete()

2.10.4 Testing Database Connectivity


Use Django’s check command to test database configuration:
python manage.py check

2.11 Django Middleware


Django middleware is a framework component that processes requests and
responses globally in a web application. Middleware acts as a layer between the
Django application and the server, allowing developers to process data during the
request-response lifecycle.
Django middleware is a framework component that processes requests and
responses globally in a web application. Middleware acts as a layer between the

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 53


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

Django application and the server, allowing developers to process data during the
request-response lifecycle.
Middleware is a lightweight, pluggable layer of logic that is executed during the
processing of HTTP requests and responses. It allows for various functionalities such
as request preprocessing, response postprocessing, and exception handling.

2.11.1 Role of Middleware in Django


Middleware can:
• Modify incoming requests before they reach the view.
• Modify outgoing responses before they are sent to the client.
• Process exceptions raised during the request-response cycle.
• Perform cross-cutting concerns such as authentication, session handling, or
security checks.
2.11.2 Advantages of Middleware
• Centralized Logic: Middleware allows the implementation of global functionality
across the application.
• Reusability: Middleware can be reused across projects.
• Flexibility: Custom middleware enables developers to tailor the request-response
lifecycle.
• Separation of Concerns: Middleware separates cross-cutting concerns from core
application logic.

2.11.3 Middleware Lifecycle


a. Initialization
• The __init__() method is executed once when the server starts. It initializes
the middleware and accepts the get_response argument.
b. Request Processing
• Middleware can modify or block the request before it reaches the view by
implementing process_request().
c. View Processing
• Middleware can interact with the selected view using process_view().
d. Response Processing
• Middleware can modify the response after it is generated by the view using
__call__() or process_template_response().
e. Exception Handling
• Middleware can handle exceptions raised in views or other middleware using
process_exception().

2.11.4 Default Middleware in Django


Django comes with several built-in middleware classes, which are defined in the
MIDDLEWARE setting in settings.py.
Example:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 54


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
a. SecurityMiddleware
Provides security enhancements like HTTP Strict Transport Security (HSTS).
b. SessionMiddleware
Manages session data across requests.
c. CommonMiddleware
Handles common tasks such as appending slashes to URLs or managing URL
redirects.
d. CsrfViewMiddleware
Adds Cross-Site Request Forgery (CSRF) protection to requests.
e. AuthenticationMiddleware
Associates users with requests, enabling user authentication.
f. MessageMiddleware
Handles messages sent to users during the request-response cycle.
g. XFrameOptionsMiddleware
Prevents the site from being embedded in an iframe to protect against
clickjacking.

2.11.5 Writing Custom Middleware


Developers can create custom middleware for specific functionality not covered by
Django's built-in middleware.
a. Structure of Middleware
A middleware class must:
• Be defined as a Python class.
• Implement at least one of the following methods:
o __init__(self, get_response)
o __call__(self, request)
o process_request(self, request) (deprecated in Django 2.0+)
o process_view(self, request, view_func, view_args, view_kwargs)
o process_exception(self, request, exception)
o process_template_response(self, request, response)
b. Example Custom Middleware
• Adding a Custom Header to All Responses:
class CustomHeaderMiddleware:

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 55


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

def __init__(self, get_response):


self.get_response = get_response

def __call__(self, request):


response = self.get_response(request)
response['X-Custom-Header'] = 'My Custom Value'
return response

• Registering Middleware
Custom middleware must be added to the MIDDLEWARE setting in
settings.py.
Example:
MIDDLEWARE = [
'myapp.middleware.CustomHeaderMiddleware',
'django.middleware.security.SecurityMiddleware',
# Other middleware...
]

2.12 Session
All communication between web browsers and servers is via HTTP, which is stateless.
The fact that the protocol is stateless means that messages between the client and
server are completely independent of each other — there is no notion of "sequence"
or behavior based on previous messages. As a result, if you want to have a site that
keeps track of the ongoing relationships with a client, you need to implement that
yourself.
Sessions are the mechanism used by Django (and most of the Internet) for keeping
track of the "state" between the site and a particular browser. Sessions allow you to
store arbitrary data per browser, and have this data available to the site whenever
the browser connects. Individual data items associated with the session are then
referenced by a "key", which is used both to store and retrieve the data.
Django uses a cookie containing a special session id to identify each browser and its
associated session with the site. The actual session data is stored in the site database
by default (this is more secure than storing the data in a cookie, where they are more
vulnerable to malicious users). You can configure Django to store the session data in
other places (cache, files, "secure" cookies), but the default location is a good and
relatively secure option.
2.12.1 Enabling sessions
Sessions were enabled automatically when we created the skeleton website. The
configuration is set up in the INSTALLED_APPS and MIDDLEWARE sections of the
project file (settings.py), as shown below:
INSTALLED_APPS = [
#…

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 56


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

'django.contrib.sessions',
#…
MIDDLEWARE = [
#…
'django.contrib.sessions.middleware.SessionMiddleware',
# …]

2.12.2 Using sessions


You can access the session attribute within a view from the request parameter (an
HttpRequest passed in as the first argument to the view). This session attribute
represents the specific connection to the current user (or to be more precise, the
connection to the current browser, as identified by the session id in the browser's
cookie for this site).
The session attribute is a dictionary-like object that you can read and write as many
times as you like in your view, modifying it as wished. You can do all the normal
dictionary operations, including clearing all data, testing if a key is present, looping
through data, etc. Most of the time though, you'll just use the standard "dictionary"
API to get and set values.
The code fragments below show how you can get, set, and delete some data with the
key my_car, associated with the current session (browser).
# Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is
not present
my_car = request.session['my_car']
# Get a session value, setting a default if it is not present ('mini')
my_car = request.session.get('my_car', 'mini')
# Set a session value
request.session['my_car'] = 'mini'
# Delete a session value
del request.session['my_car']
The API also offers a number of other methods that are mostly used to manage the
associated session cookie. For example, there are methods to test that cookies are
supported in the client browser, to set and check cookie expiry dates, and to clear
expired sessions from the data store.

2.12.3 Saving session data


By default, Django only saves to the session database and sends the session cookie to
the client when the session has been modified (assigned) or deleted. If you're
updating some data using its session key as shown in the previous section, then you
don't need to worry about this! For example:
# This is detected as an update to the session, so session data is saved.
request.session['my_car'] = 'mini'

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 57


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

If you're updating some information within session data, then Django will not
recognize that you've made a change to the session and save the data (for example, if
you were to change wheels data inside your my_car data, as shown below). In this
case you will need to explicitly mark the session as having been modified.
# Session object not directly modified, only data within the session. Session
changes not saved!
request.session['my_car']['wheels'] = 'alloy'
# Set session as modified to force data updates/cookie to be saved.
request.session.modified = True

2.12.4 Simple example — getting visit counts


As a simple real-world example we'll update our library to tell the current user how
many times they have visited the LocalLibrary home page.
Open /django-locallibrary-tutorial/catalog/views.py, and add the lines that contain
num_visits into index() (as shown below).
def index(request):
#…
num_authors = Author.objects.count() # The 'all()' is implied by default.
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
num_visits += 1
request.session['num_visits'] = num_visits
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context
variable.
return render(request, 'index.html', context=context)
Here we first get the value of the 'num_visits' session key, setting the value to 0 if it
has not previously been set. Each time a request is received, we then increment the
value and store it back in the session (for the next time the user visits the page). The
num_visits variable is then passed to the template in our context variable.

Add the line shown at the bottom of the following block to your main HTML template
(/django-locallibrary-tutorial/catalog/templates/index.html) at the bottom of the
"Dynamic content" section to display the num_visits context variable.
<h2>Dynamic content</h2>
<p>The library has the following record counts:</p>

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 58


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

<ul>
<li><strong>Books:</strong> {{ num_books }}</li>
<li><strong>Copies:</strong> {{ num_instances }}</li>
<li><strong>Copies available:</strong> {{ num_instances_available }}</li>
<li><strong>Authors:</strong> {{ num_authors }}</li>
</ul>
<p>
You have visited this page {{ num_visits }} time{{ num_visits|pluralize }}.
</p>

Note that we use the Django built-in template tag pluralize to add an "s" when the
page has been visited multiple times. Save your changes and restart the test server.
Every time you refresh the page; the number should update.

2.13 Cookies
Cookies, technically called HTTP Cookies are small text files which are created and
maintained by your browser on the particular request of Web-Server. They are stored
locally by your browser, and most browser will also show you the cookies generated
in the Privacy and Security settings of the browser. HTTP is a stateless protocol. When
any request is sent to the server, over this protocol, the server cannot distinguish
whether the user is new or has visited the site previously. Suppose, you are logging in
any website, that website will respond the browser with some cookies which will
have some unique identification of user generated by the server and some more
details according to the context of the website. Cookies made these implementations
possible with ease which were previously not possible over HTTP implementation.

2.13.1 How do Cookies work?


Cookies work like other HTTP requests over the Internet. In a typical web-system, the
browser makes a request to the server. The server then sends the response along
with some cookies, which may contain some login information or some other data.
When the browser makes a new request, the cookie generated previously is also
transmitted to the server. This process is repeated every time a new request is made
by the browser. The browser repeats the process until the cookie expires or the
session is closed and the cookie is deleted by the browser itself. Then, the cookie
applies in all sorts of tasks, like when your login to a website or when shopping online
on the web. Google AdSense and Google Analytics can also track you using the
cookies they generate. Different websites use cookies differently according to their
needs.
a. Setting Cookies:
def set_cookie_view(request):
response = HttpResponse("Cookie Set!")
response.set_cookie('key', 'value', max_age=3600) # Expires in 1 hour

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 59


B.Sc. III Sem.VI (CBCS) (NEP 1.0) CS P-XVI ADVANCED PYTHON DSE-24F

return response
b. Getting Cookies:
def get_cookie_view(request):
value = request.COOKIES.get('key', 'default_value')
return HttpResponse(f"The value of the cookie is: {value}")
c. Deleting Cookies:
def delete_cookie_view(request):
response = HttpResponse("Cookie Deleted!")
response.delete_cookie('key')
return response

Prof. N. S. Kulkarni (Cell: 9890966539/9096194081) 60

You might also like