
--- PDF page 91 ---
UNIT 2 · BACK-END DEVELOPMENT




       02
       Python, Django, REST APIs & ML
       The server side of every web app, built from zero: the Python you need (collections, muta‐
       bility, OOP), raw sockets and files, then Django end to end: models, the ORM, views, tem‐
       plates, forms, login and sessions, PostgreSQL, a JSON API with Django REST Framework,
       and a trained ML model served from a Django page. Every past-paper question on this unit
       is answered in full, in the form you should write it.

          104 marks asked in 3 papers            14 PYQs solved        5 gaps filled        11 drills




 1. Python core: types, collections, functions                       11. Views, URLs and the three response types
 2. Mutability, aliasing and copying                                 12. Templates: DTL, inheritance, static, CSRF
 3. OOP: classes, objects and methods                                13. Django forms and POST handling
 4. Networking with Python: sockets and HTTP                         14. Authentication, authorization and sessions
 5. File I/O and JSON                                                15. Database connectivity
 6. Django from zero: MVT and the request cycle                      16. Django REST Framework
 7. Project vs app: the full project structure                       17. Machine-learning model integration
 8. Setting up a project, an app and the admin                       18. Case study: the Enrollments system
 9. Models, fields, relationships and migrations                     19. Likely questions for 2026
10. The ORM in the Django shell                                      20. Last-minute recap




   ✍️ WHERE THE MARKS ARE IN THIS UNIT
   Unit 2 carried 44 of 100 marks in the newest paper (Final 2025-26: Q1d 4 M, all of Q3 = 20 M, all of Q7 =
   20 M). The older papers asked full 10-mark Django code questions (models + shell queries, DRF, ML +
   form, MVT + structure, project setup). The 2025-26 Q3 was pure Python (lists, tuples, mutability, OOP) and
   most of it is not in your notes. That gap is taught in full in 2.1–2.3.              🔥 HIGH PRIORITY Q3 and Q7 are two
   complete 20-mark questions you can choose. Prepare both.




     2.1 Python core: types, collections, functions
📚 Sources: Unit 2 Notes §2.1–2.2       LEC 4 (Python · Django) slides 4–5    One-Shot Revision · Python core

  Complete Revision deck U2 slide 12   Not in your files: collections, comprehensions (added from standard references)

--- PDF page 92 ---
🧠 START FROM ZERO
  Python is an interpreted, dynamically typed language: you never declare a type, the value carries its own
  type, and blocks are marked by indentation rather than braces. In Python everything is an object (num‐
  bers, strings, lists, functions, classes), and a variable is just a name tag stuck on an object. Keep that last
  sentence in mind. It explains aliasing, copying and mutability in 2.2.



▸ Built-in data types at a glance

 Type            Example literal           Mutable?    Ordered?                Duplicates?    Typical use

 int / float      42 , 3.14                No          n/a                     n/a            counts, marks, prices

 bool             True , False             No          n/a                     n/a            flags ( is_active )

 str              "Asha"                   No          Yes                     Yes            text

 NoneType         None                     No          n/a                     n/a            "no value" (SQL NULL)

 list             [1, 2, 2]                Yes         Yes                     Yes            a changing sequence

 tuple            (1, 2, 2)                No          Yes                     Yes            a fixed record, e.g. (lat,
                                                                                              lng)

 dict             {"roll": 7}              Yes         Yes (insertion order,   keys unique    look up a value by key
                                                       3.7+)

 set              {1, 2}                   Yes         No                      No             uniqueness, membership tests

 frozenset        frozenset({1,            No          No                      No             a set that can be a dict key
                 2})



▸ The four collections: list, tuple, dict, set

               collections.py: the operations you must know


  # LIST: ordered, mutable, allows duplicates
  nums = [4, 1, 3]
  nums.append(5)                   # [4, 1, 3, 5]        add at end
  nums.insert(0, 9)                # [9, 4, 1, 3, 5]     add at index
  nums.remove(1)                   # [9, 4, 3, 5]        remove first matching VALUE
  last = nums.pop()                # last = 5, nums = [9, 4, 3]
  nums.sort()                      # [3, 4, 9]           sorts IN PLACE (returns None)
  nums[0] = 100                    # allowed: lists are mutable
  print(nums[1:3])                 # slicing -> [4, 9]


  # TUPLE: ordered, IMMUTABLE
  point = (19.07, 72.87)
  lat, lng = point                 # tuple unpacking
  # point[0] = 0                   # TypeError: 'tuple' object does not support item assignment
  single = (5,)                    # a one-element tuple needs the comma


  # DICT: key -> value mapping, keys unique and hashable

--- PDF page 93 ---
student = {"name": "Asha", "marks": 78}
  student["marks"] = 85                         # update
  student["city"] = "Mumbai"                    # insert a new key
  print(student.get("age", "NA"))               # NA      (no KeyError, returns the default)
  for key, value in student.items():            # loop over pairs
        print(key, value)


  # SET: unordered, unique items
  tags = {"python", "django", "python"}           # duplicate dropped -> {'python', 'django'}
  a, b = {1, 2, 3}, {3, 4}
  print(a | b, a & b, a - b, a ^ b)               # {1, 2, 3, 4} {3} {1, 2} {1, 2, 4}
  print(2 in a)                                   # True: very fast membership test
  empty_dict, empty_set = {}, set()               # {} is a DICT, not a set!




  LIST VS TUPLE                                                    DICT VS SET

       List [ ] : mutable, so you can append, re‐                      Dict: key → value pairs. Use it when you look
       move and change items. Many methods.                            something up by a key (roll no → student).
       Tuple ( ) : immutable, fixed after creation.                    Set: just unique values, no values attached.
       Only count() and index() .                                      Use it to remove duplicates, test membership,
       Tuple is slightly faster and smaller, and is                    or do union / intersection.
       hashable (if its items are), so it can be a dict                Both are hash tables: lookup is O(1) on aver‐
       key or set item.                                                age, and keys / items must be hashable.
       Use a list for a changing collection (cart items).              {} is an empty dict; an empty set is set() .
       Use a tuple for a fixed record (RGB colour, co‐
       ordinates, a DB row).



▸ Comprehensions: build a collection in one line

           comprehensions.py


  squares = [n * n for n in range(5) if n % 2 == 0]                # [0, 4, 16]
  sq_map     = {n: n * n for n in range(3)}                        # {0: 0, 1: 1, 2: 4}
  letters = {c for c in "banana"}                                  # {'a', 'b', 'n'}
  names      = [s["name"].upper() for s in [{"name": "asha"}, {"name": "ravi"}]]                # ['ASHA', 'RAVI']




▸ Functions, default arguments, *args and **kwargs
A function is defined with def , can have default values, and can be called with keyword arguments in any or‐
der. A lambda is a one-line anonymous function ( key=lambda s: s["marks"] ). The course stresses one more
idea: functions that accept any number of arguments.

           args_kwargs.py (course example: Unit 2 Notes §2.1, LEC 4 slide 4)


  def order_pizza(size, *toppings, **extras):
        print(size, toppings, extras)

--- PDF page 94 ---
order_pizza("L", "olive", "corn", cheese=True)
  # L ('olive', 'corn') {'cheese': True}


  # the same symbols UNPACK at the call site:
  order_pizza("L", *["olive", "corn"], **{"cheese": True})                      # identical call



 Parameter                 Role                                                          Value in the call above

  size                     normal positional parameter                                    "L"

  *toppings                extra positional args collected into a tuple                   ("olive", "corn")

  **extras                 extra keyword args collected into a dict                       {"cheese": True}


Django uses this everywhere: a URL like /orders/7/ calls order_detail(request, pk=7) , so the captured
value arrives as a keyword argument. Form and serializer classes accept *args, **kwargs and pass them up
with super().__init__(*args, **kwargs) .


▸ Exception handling: try / except / else / finally

 Block                      Runs when

  try                       Always. This is the risky code being attempted.

  except                    Only if an error matching its type happened inside try .

  else                      Only if try finished with no error.

  finally                   Always, error or not. Use it for cleanup.


           exceptions.py


  def safe_divide(a, b):
         try:
             result = a / b
         except ZeroDivisionError as e:                  # catch a SPECIFIC error, never a bare "except:"
             print("Error:", e)
             return None
         else:
             print("No error")
             return result
         finally:
             print("finally always runs")


  safe_divide(10, 2)         # No error -> finally always runs -> returns 5.0
  safe_divide(1, 0)          # Error: division by zero -> finally always runs -> returns None
  # raise ValueError("bad input")              -> throw an error yourself; custom: class MyError(Exception):
  pass

--- PDF page 95 ---
⚠️ COMMON MISTAKE
  A bare except: catches everything, including bugs you want to see (a typo becoming NameError ), and
  hides them. Always name the error type. Several except blocks are checked top to bottom, and only the
  first match runs. Django uses the same idea: get_object_or_404 raises Http404 , and Django turns it
  into a proper 404 page instead of a crash.




    2.2 Mutability, aliasing and copying
📚 Sources: Not in your files: added from standard references   Unit 2 Notes §2.3 (only attributes per instance)


    🚨 NOT IN YOUR STUDY MATERIAL · 20 MARKS · FINAL 2025-26 Q3(A, B, C)
    What's missing: none of your 22 study files explains list vs tuple, dict vs set, mutable vs immutable,
    aliasing vs .copy() , shallow vs deep copy, hashability, class/static methods or destructors. Only
       __init__ , self and "constructor" appear (Unit 2 Notes §2.3, One-Shot).

    Verdict: MUST LEARN. This was a whole 20-mark question in the newest paper, it is short and fully pre‐
    dictable, and it reappears inside Django questions (QuerySets, form data, default arguments). Sections
    2.1–2.3 teach all of it.



▸ Names, objects, id() and "is" vs "=="
Every object has an identity (where it lives in memory, shown by id(obj) ), a type and a value. A variable is
only a name that refers to an object. Two operators compare different things:

 Operator         Asks                                                    Example

  ==              Do the two objects have equal values?                    [1, 2] == [1, 2] → True

  is              Are they the same object (same id )?                     [1, 2] is [1, 2] → False (two lists)


Use is only for None checks ( if x is None: ). Use == for values.


▸ Mutable vs immutable
A mutable object can be changed in place: same object, same id , new contents. An immutable object can
never change. Any "change" builds a new object and moves the name to it.

                               Mutable                                             Immutable

  Examples                      list , dict , set , bytearray ,                     int , float , bool , str , tuple ,
                               most user-defined objects                            frozenset , bytes , None

  In-place change?             Yes: append , d[k] = v , add                        No: s.upper() returns a NEW string

  Effect on aliases            All names sharing it see the change                 Other names are never affected

  Hashable (dict key /         No                                                  Yes (a tuple only if all its items are hashable)
  set item)?

--- PDF page 96 ---
immutable_rebinding.py


  n = 10
  m = n                 # m and n name the same int object
  m += 1                # ints can't change, so Python builds 11 and moves only "m"
  print(n, m)           # 10 11


  s1 = "cat"
  s2 = s1
  s2 += "s"             # a NEW string "cats" is created for s2
  print(s1, s2)         # cat cats


  t = (1, [2, 3])            # a tuple holding a list
  t[1].append(4)             # allowed! the tuple is unchanged; the LIST inside changed
  print(t)                   # (1, [2, 3, 4])
  # t[0] = 9                # TypeError: 'tuple' object does not support item assignment




▸ Aliasing vs copying
Aliasing means two or more names refer to one object. Plain assignment y = x never copies anything; it only
adds a second name tag. Copying builds a new object, so changes to one no longer show up in the other.

                         Aliasing: y = x                                           Copying: w = z.copy()


          x                                                                   z                      [5, 6, 7]

                                     [1, 2, 3, 4]

          y                       ONE list object (same id)                   w                   [5, 6, 7, 8]

                                                                                               TWO separate list objects


                             Assignment adds a name to the same object; .copy() creates a new object.



▸ Shallow copy vs deep copy
A shallow copy builds a new outer container but puts the same inner objects inside it. A deep copy
( copy.deepcopy ) copies recursively, so nested lists and dicts are duplicated too. For a flat list of numbers or
strings the two behave the same. They differ only when the items are themselves mutable.

                                                                 New outer         New inner            Changes to inner lists
 How
                                                                 object?           objects?             shared?

  b = a (assignment)                                             No (alias)        No                   Yes, everything is shared

  a.copy() , list(a) , a[:] , copy.copy(a) ,                     Yes               No                   Yes
  dict(d) , d.copy()

  copy.deepcopy(a)                                               Yes               Yes                  No, fully independent

--- PDF page 97 ---
shallow_vs_deep.py (verified output in comments)


  import copy


  a = [[1, 2], [3, 4]]
  s = a.copy()               # shallow: new outer list, SAME inner lists
  d = copy.deepcopy(a)       # deep: everything duplicated


  s[0].append(99)             # changes the inner list shared by a and s
  d[1].append(77)             # changes d's private inner list only
  s.append([5])               # changes s's outer list only


  print(a)       # [[1, 2, 99], [3, 4]]
  print(s)       # [[1, 2, 99], [3, 4], [5]]
  print(d)       # [[1, 2], [3, 4, 77]]




▸ Hashability: why dict keys must be immutable
A dict (and a set) is a hash table. To store a key, Python computes hash(key) , a number that decides which
"bucket" the entry goes into. To find the key later it recomputes the hash and looks in that bucket. If a key could
change after insertion, its hash would change, the dict would look in the wrong bucket, and the entry would be
lost. So Python only accepts hashable keys, meaning objects whose hash never changes during their lifetime.
In practice that means immutable ones.

           hashable.py


  ok = {(19.07, 72.87): "Mumbai", "roll": 7, 42: "answer"}           # tuple, str, int keys: fine
  bad = {[1, 2]: "x"}              # TypeError: unhashable type: 'list'
  bad2 = {(1, [2]): "x"}           # TypeError: unhashable type: 'list'      (tuple contains a list)
  visited = set()
  visited.add(frozenset({"a", "b"}))           # frozenset is the hashable version of set




▸ Mutability and functions
Python passes arguments by object reference: the parameter becomes another alias for the caller's object. A
function that mutates a list argument changes the caller's list. The classic trap is a mutable default argument,
which is created once when the function is defined and then shared by every call:

           default_arg_trap.py


  def add_item(item, bag=[]):                # BAD: one list shared by all calls
        bag.append(item)
        return bag
  print(add_item("pen"))         # ['pen']
  print(add_item("book"))        # ['pen', 'book']     surprise!


  def add_item(item, bag=None):              # GOOD: make a fresh list per call

--- PDF page 98 ---
if bag is None:
               bag = []
        bag.append(item)
        return bag




   ✏️ PREDICT THE OUTPUT
                no running allowed: write the 5 printed lines


       p = [10, 20]
       q = p
       r = p[:]
       q.append(30)
       r.append(40)
       print(p)                     # (1)
       print(p is q, p is r, p == [10, 20, 30])                       # (2)
       t = ("a", ["b"])
       t[1].append("c")
       print(t)                     # (3)
       x = "hi"; y = x; y = y + "!"
       print(x)                     # (4)
       print(len({1, 1, 2, (3, 4), (3, 4)}))                      # (5)



   🔓 Answer key: (1) [10, 20, 30] · (2) True False True · (3) ('a', ['b', 'c']) · (4) hi · (5) 3, because the set keeps 1, 2 and (3, 4) once each

   PYQ         Final 2025-26 · Q3(B)   ★ LATEST                                                                                                6M


  Code reading (no execution): What prints in each case and why? Explain aliasing vs copying in detail.

    x = [1, 2, 3]
    y = x
    y.append(4)
    print(x)

    z = [5, 6, 7]
    w = z.copy()
    w.append(8)
    print(z)



   ✓    MODEL ANSWER: WRITE THIS

  Output:

                output


       [1, 2, 3, 4]
       [5, 6, 7]

--- PDF page 99 ---
Case 1: aliasing. x = [1, 2, 3] creates one list object and binds the name x to it. y = x does not
  copy the list; it binds a second name y to the same object, so x is y is True and id(x) == id(y) .
  Lists are mutable and append() changes the object in place, so the change made "through" y is visible
  through x . Hence print(x) shows [1, 2, 3, 4] .

  Case 2: copying. z.copy() creates a new list object with the same elements, and w refers to that new
  object, so w is z is False . Appending 8 changes only w (which becomes [5, 6, 7, 8] ), and z is
  untouched, so print(z) shows [5, 6, 7] .

  Aliasing vs copying in detail:

                                            Aliasing ( y = x )                                 Copying ( w = z.copy() )

    Objects in memory                       One object, two names                              Two separate objects

       is / id()                                x is y → True, same id                          w is z → False, different ids

    In-place change via one name            Seen through every alias                           Not seen by the other

    Cost                                    Free (no memory used)                              Extra memory and time to copy

    Use when                                You want to share and update one object            You need an independent version


    list.copy() (also list(z) , z[:] , copy.copy(z) ) is a shallow copy: only the outer list is new, and
  nested mutable items are still shared. For lists containing lists or dicts, use copy.deepcopy() to get a fully
  independent copy. Aliasing matters only for mutable objects: with immutable ones (int, str, tuple) every
  "change" creates a new object, so aliases can never affect each other.

  🎯 Marking scheme guess: 1 M each output · 2 M aliasing (same object, mutable, in place) · 2 M copy (new object) + shallow/deep note

   PYQ       Final 2025-26 · Q3(C)   ★ LATEST                                                                                    4M


  Mutable vs immutable objects in Python. Three examples of each. Why does immutability matter for
  dictionary keys?

   ✓    MODEL ANSWER: WRITE THIS

  A mutable object can be modified in place after it is created: its identity ( id ) stays the same while its con‐
  tents change. An immutable object can never change after creation. Any operation that seems to change it
  actually creates a new object.

        Mutable: list ( L.append(4) ), dict ( d["k"] = 1 ), set ( s.add(5) ); also user-defined objects
        and bytearray .
        Immutable: int , str ( s.upper() returns a new string), tuple ; also float , bool , frozenset ,
         bytes .

              example


       nums = [1, 2]; nums.append(3)                 # same list object, now [1, 2, 3]
       name = "asha"; name = name.title() # a NEW str "Asha"; the old "asha" is unchanged

--- PDF page 100 ---
Why it matters for dict keys: a dict is a hash table. It stores each key in a slot chosen by hash(key) and
  finds it again by recomputing that hash. If a key could be mutated after insertion, its hash would change
  and the dict could no longer find (or would duplicate) the entry. Python therefore requires keys to be hash‐
  able, meaning their hash never changes, which in practice means immutable: {(1, 2): "a"} works, but
    {[1, 2]: "a"} raises TypeError: unhashable type: 'list' . The same rule applies to set elements. A
  tuple is a valid key only if all its items are immutable too.

  🎯 Marking scheme guess: 1 M definitions · 1 M three + three examples · 2 M hashing explanation with the TypeError example


    2.3 OOP: classes, objects and methods
📚 Sources: Unit 2 Notes §2.3–2.6     LEC 4 (Python · Django) slides 6–8     One-Shot Revision · OOP      Complete Revision deck U2 slide 13


  💡 THINK OF IT LIKE
  A class is the architect's blueprint of a flat; an object (instance) is one actual flat built from it. Every flat has
  the same layout (methods) but its own furniture (attribute values). self is the flat number on the door: it
  says "this particular flat".



▸ Class, object, __init__ and self

           dog.py (course example: Unit 2 Notes §2.3, LEC 4 slide 6)


  class Dog:
        species = "Canis familiaris"                 # CLASS attribute: one value shared by every Dog


        def __init__(self, name):                    # constructor: runs automatically on Dog(...)
             self.name = name                        # INSTANCE attribute: separate for each object


        def bark(self):                              # instance method: self = the object it is called on
             return f"{self.name} says woof"


  rex, milo = Dog(name="Rex"), Dog(name="Milo")
  print(rex.bark())            # Rex says woof
  print(milo.bark())           # Milo says woof          (same method, different self)
  print(rex.species, Dog.species)                    # shared class attribute



     __init__ is the constructor (strictly, the initialiser). It runs automatically the moment an object is created
    and sets that object's starting state.
     self is the first parameter of every instance method. It refers to the specific instance the method was
    called on. You never pass it yourself: rex.bark() is really Dog.bark(rex) . The name self is a conven‐
    tion, not a keyword.
    Attributes set as self.x belong to one object. Attributes written in the class body are shared by all ob‐
    jects, unless one object overrides them. This is exactly why Django model fields are written in the class
    body: they describe the whole table, not one row.

--- PDF page 101 ---
🚨 NOT IN YOUR STUDY MATERIAL · PART OF 10 MARKS · FINAL 2025-26 Q3(A)
    What's missing: instance vs class vs static methods, the destructor __del__ , garbage collection, and
      __new__ . Verdict: MUST LEARN. Two of the five parts of Q3(A) depend on it, and it is easy to score.



▸ Instance, class and static methods

           student.py (verified: the output is shown below)


  class Student:
        school = "MPSTME"                        # class attribute
        count = 0                                # counts objects created


        def __init__(self, name, marks):         # CONSTRUCTOR
             self.name = name
             self.marks = marks
             Student.count += 1
             print(f"Created {self.name}")


        def grade(self):                         # INSTANCE method: needs one object (self)
             return "A" if self.marks >= 75 else "B"


        @classmethod
        def from_csv(cls, line):                 # CLASS method: receives the class (cls)
             name, marks = line.split(",")
             return cls(name, int(marks))        # an "alternative constructor"


        @staticmethod
        def is_pass(marks):                      # STATIC method: no self, no cls
             return marks >= 40


        def __str__(self):
             return f"{self.name} ({self.marks})"


        def __del__(self):                       # DESTRUCTOR
             print(f"Deleting {self.name}")


  s1 = Student("Asha", 82)
  s2 = Student.from_csv("Ravi,64")
  print(s1.grade(), s2.grade())                               # A B
  print(Student.is_pass(35), Student.count, s1)               # False 2 Asha (82)
  del s1                                                      # Deleting Asha
  print("end of program")
  # program exits -> remaining objects are destroyed -> Deleting Ravi

--- PDF page 102 ---
Instance method           Class method                          Static method

  Decorator             none                       @classmethod                          @staticmethod

  First parameter        self (the object)         cls (the class)                      none

  Can                   that object's data (and   class-level data only                 only its arguments
  read/change           class data)

  Called as              s1.grade()                Student.from_csv(...)                 Student.is_pass(35)

  Typical use           behaviour of one object   alternative constructors, counters,   utility function that belongs logi‐
                                                  factory methods                       cally to the class



▸ Constructor and destructor
    Constructor: a special method that runs automatically when an object is created and initialises it. In Python
    that is __init__(self, ...) . Technically, object creation has two steps: __new__(cls) creates the empty
    object, then __init__(self) initialises it. You almost never write __new__ (it is used for immutable sub‐
    classes and singletons). Python has no constructor overloading, so you use default arguments or
     @classmethod alternative constructors instead.

    Destructor: __del__(self) is called when the object is about to be destroyed, i.e. when its reference
    count drops to zero, or when the cyclic garbage collector reclaims it (or at program exit). del s1 deletes
    the name; the object is destroyed only if no other name still refers to it. Because the timing is not guaran‐
    teed, real cleanup (closing files, DB connections) should use with blocks or explicit close() , not
     __del__ .


▸ Inheritance, overriding and super()

           inheritance.py (course: Unit 2 Notes §2.4, LEC 4 slide 7, One-Shot)


  class Animal:
        def __init__(self, name):
              self.name = name
        def speak(self):
              return "..."


  class Dog(Animal):                               # Dog IS-AN Animal: inherits everything
        def __init__(self, name, breed):
              super().__init__(name)               # run the parent's constructor first
              self.breed = breed
        def speak(self):                           # method OVERRIDING
              return "Woof"


  class Cat(Animal):
        def speak(self):
              return "Meow"

--- PDF page 103 ---
for pet in [Dog("Rex", "Lab"), Cat("Tom")]:                   # POLYMORPHISM: same call, different behaviour
           print(pet.name, pet.speak())                            # Rex Woof / Tom Meow



Types of inheritance: single (Dog → Animal), multilevel (Puppy → Dog → Animal), hierarchical (Dog and Cat →
Animal), multiple ( class C(A, B) , resolved left to right by the MRO). Django is built on this:
 class Order(models.Model) , class EmployeeViewSet(viewsets.ModelViewSet) ,
 class IrisForm(forms.Form) all inherit hundreds of lines of framework code, and you override only what dif‐
fers, calling super() to keep Django's own logic.


▸ Magic (dunder) methods

 Method             Powers                                                                    Called as

  __init__          runs when an object is created                                             obj = Dog()

  __str__           readable text for people (what print() shows; Django admin labels)         print(obj) , str(obj)

  __repr__          unambiguous developer text (shell, lists); fallback for __str__            repr(obj)

  __len__           the len() built-in                                                         len(obj)

  __eq__            what == means for two objects                                              a == b

  __del__           destructor (see above)                                                    object destroyed



▸ The four pillars of OOP

  Pillar                Meaning                                 Python example

  Encapsulation         Data and the methods that act on it      self._balance (internal by convention), self.__balance
                        are bundled in one class; internals     (name-mangled to _Account__balance ), access through
                        are hidden                              methods such as deposit()

  Abstraction           Callers use a simple interface with‐     dog.bark() ; Order.objects.filter(...) hides SQL
                        out knowing the internals

  Inheritance           A child class reuses and extends a       Dog(Animal) , Order(models.Model)
                        parent

  Polymorphism          The same call behaves differently        pet.speak() returns "Woof" or "Meow"
                        depending on the object



  🔑 MEMORY HOOK
  "A PIE": Abstraction, Polymorphism, Inheritance, Encapsulation. Methods: self = one object, cls = the
  class, static = neither.


   ✏️ FILL IN THE BLANKS
               complete the class so the last two lines print "2" and "True"


      class Course:
             total = 0

--- PDF page 104 ---
def ______(self, code, credits):                           # (1)
                  ______.code = code                                   # (2)
                  self.credits = credits
                  Course.total += 1


            ______                                                     # (3) decorator
            def how_many(______):                                      # (4)
                  return cls.total


            @staticmethod
            def valid_credits(______):                                 # (5)
                  return 1 <= n <= 6


            def ______(self):                                          # (6) what print(course) shows
                  return f"{self.code} ({self.credits} cr)"


       Course("CS101", 4); Course("DS201", 3)
       print(Course.how_many())
       print(Course.valid_credits(4))



   🔓 Answer key: (1) __init__ · (2) self · (3) @classmethod · (4) cls · (5) n · (6) __str__

   PYQ        Final 2025-26 · Q3(A)   ★ LATEST                                                                              10 M


  In plain words: list vs tuple (mutability) with example each; dict vs set, when to use each; purpose of
  __init__ and what self means; difference between instance method and class method; what is a con‐
  structor and destructor in Python.

   ✓    MODEL ANSWER: WRITE THIS


  1. LIST VS TUPLE (2 M)

  Both are ordered sequences that allow duplicates and indexing. A list ( [ ] ) is mutable: items can be
  added, removed or changed after creation. A tuple ( ( ) ) is immutable: once created it cannot change.
  Tuples are slightly faster and lighter, and because they are hashable (when their items are) they can be used
  as dict keys. Use a list for a collection that changes, and a tuple for a fixed record.

               example


       marks = [70, 85]; marks.append(90)                        # list -> [70, 85, 90]
       point = (19.07, 72.87)                                    # tuple
       # point[0] = 0        -> TypeError: 'tuple' object does not support item assignment

--- PDF page 105 ---
2. DICT VS SET (2 M)

  A dict stores key → value pairs with unique keys, e.g. {"roll": 7, "name": "Asha"} . Use it when you
  need to look up a value by a key (student by roll number, settings, JSON data). A set stores unique values
  only, unordered, e.g. {"python", "django"} . Use it to remove duplicates, for fast membership tests
  ( x in s ), and for union / intersection / difference. Both are hash tables with O(1) average lookup, and both
  require hashable (immutable) keys or elements. Note that {} is an empty dict, while an empty set is
    set() .


  3. PURPOSE OF __INIT__ AND MEANING OF SELF (2 M)
    __init__ is the special method Python calls automatically right after an object is created. Its purpose is to
  initialise the object's state, i.e. to set the instance attributes from the arguments: Student("Asha", 82)
  runs __init__(self, "Asha", 82) . self is a reference to the current instance, the particular object on
  which a method is called. It is the first parameter of every instance method; Python passes it automatically
  ( s1.grade() = Student.grade(s1) ), and it is how each object keeps its own data ( self.name ).

  4. INSTANCE METHOD VS CLASS METHOD (2 M)

                        Instance method                      Class method

    Definition          plain def m(self, ...)                @classmethod + def m(cls, ...)

    Bound to            an object                            the class itself

    Accesses            instance data (and class data)       class data only, no instance data

    Called as            s1.grade()                           Student.from_csv("Ravi,64")

    Use                 behaviour of one object              alternative constructors, class-wide counters


  (A static method, @staticmethod , takes neither self nor cls ; it is a plain utility function kept inside
  the class.)

  5. CONSTRUCTOR AND DESTRUCTOR (2 M)

  A constructor is a special method executed automatically when an object is created, used to initialise it. In
  Python it is __init__() (the object itself is created just before by __new__() ). A destructor is a special
  method executed when an object is about to be destroyed. In Python it is __del__() , called when the ob‐
  ject's reference count reaches zero (e.g. after del obj removes the last reference) or when the garbage
  collector frees it. Python manages memory automatically, so destructors are rarely needed, and their timing
  is not guaranteed.

                one example covering 3, 4 and 5


     class Student:
           count = 0                                         # class attribute
           def __init__(self, name, marks):                  # constructor
                 self.name, self.marks = name, marks         # self = this object
                 Student.count += 1
           def grade(self):                                  # instance method
                 return "A" if self.marks >= 75 else "B"
           @classmethod

--- PDF page 106 ---
def total(cls):                                              # class method
                 return cls.count
           def __del__(self):                                           # destructor
                 print("Deleting", self.name)


     s = Student("Asha", 82)
     print(s.grade(), Student.total())                  # A 1
     del s                                              # Deleting Asha



  🎯 Marking scheme guess: 2 M per part: list/tuple · dict/set · __init__/self · instance/class method · constructor/destructor (an example in
  each part earns the full 2)




    2.4 Networking with Python: sockets and HTTP
📚 Sources: Unit 2 Notes §3.1–3.3, §3.5       LEC 4 (Python · Django) slides 10–12      One-Shot Revision · Sockets & HTTP

 Complete Revision deck U2 slide 14


  🧠 START FROM ZERO
  Two programs on a network talk through sockets. A socket is the endpoint of a connection on each side,
  identified by an IP address + port (for example 192.168.1.4:51342 for the client and
    143.110.x.x:8000 for the server). The IP finds the machine; the port picks which program ("door") on it.
  Common ports: 80 HTTP, 443 HTTPS, 8000 Django runserver , 5432 PostgreSQL. HTTP, and therefore
  Django, is just a text protocol spoken over a TCP socket.


 Side      Calls in order                                                    What each does

 Client      socket() → connect() → send()/recv() →                          create an endpoint → reach the server → exchange bytes →
             close()                                                         release

 Server      socket() → bind() → listen() →                                  claim IP + port → start queueing clients → wait for one (returns
             accept() → recv()/send() → close()                              a new socket for that client) → talk → close


 AF_INET = IPv4 addresses; SOCK_STREAM = TCP, a reliable, ordered byte stream (what HTTP needs). The al‐
ternative SOCK_DGRAM = UDP (fast, no delivery guarantee: video calls, DNS).

           echo_server.py (run first, in terminal 1)


  import socket


  server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server.bind(("127.0.0.1", 9000))                      # claim an IP + port
  server.listen(5)                                      # start listening, queue up to 5 clients
  print("Waiting...")
  conn, addr = server.accept()                          # blocks until a client connects; conn = new socket
  data = conn.recv(1024)                                # read up to 1024 BYTES
  conn.send(b"Echo: " + data)                           # reply, also in bytes

--- PDF page 107 ---
conn.close()
  server.close()



           echo_client.py (run second, in terminal 2)


  import socket


  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(("127.0.0.1", 9000))                     # reach the server
  s.send("hello".encode())                           # str -> bytes
  reply = s.recv(1024).decode()                      # bytes -> str
  print(reply)                                       # Echo: hello         (tested)
  s.close()



Sockets carry bytes, not text, which is why strings are .encode() d before sending and .decode() d after re‐
ceiving (or written as b"..." ). python manage.py runserver is, at its core, this same loop: accept a connec‐
tion, read the request text, hand it to Django, send the response back.


▸ HTTP is text over that socket

           anatomy of a request and its response (LEC 4 slide 12)


  GET /api/orders/42 HTTP/1.1                       <- method, path, version
  Host: example.com                                 <- headers
  Authorization: Bearer <token>


  HTTP/1.1 200 OK                                   <- status line
  Content-Type: application/json
                                                    <- blank line, then the body
  {"id": 42, "item": "samosa", "paid": true}




▸ HTTP methods and status codes

 Method         Intent                                   Idempotent?                          Django / DRF use

 GET            read a resource                          Yes (and safe: changes nothing)      show a page, list, retrieve

 POST           create a resource / submit a form        No                                   form submit, create

 PUT            replace a resource                       Yes                                  DRF update

 PATCH          partly update a resource                 No (in general)                      DRF partial_update

 DELETE         remove a resource                        Yes                                  DRF destroy


Idempotent = repeating the request has the same effect as doing it once. That is why anything that creates data
(an order, an enrollment) is sent as POST, never GET. HTML forms can send only GET and POST.

--- PDF page 108 ---
Code                           Meaning                                    When you see it in this unit

 200 OK                         success                                    a page or JSON returned

 201 Created                    new resource made                          DRF POST /api/employees/

 204 No Content                 success, empty body                        DRF DELETE

 302 Found                      redirect                                       redirect() after a form POST; @login_required send‐
                                                                           ing you to login

 400 Bad Request                invalid input                              serializer is_valid(raise_exception=True) fails

 401 Unauthorized               not authenticated                          DRF view with IsAuthenticated , no token sent

 403 Forbidden                  authenticated but not allowed / CSRF       POST form without {% csrf_token %} ; missing permission
                                failed

 404 Not Found                  no such resource                               get_object_or_404 , unknown URL

 405 Method Not                 wrong HTTP method                              @require_POST view hit with GET
 Allowed

 500 Server Error               unhandled exception                        a bug in your view




      2.5 File I/O and JSON
📚 Sources: Unit 2 Notes §3.4, §3.6          LEC 4 (Python · Django) slide 13      One-Shot Revision · Files     Complete Revision deck U2 slide 12

 LEC 5 (Django code-along) step 20 (pathlib)


 Mode          Behaviour                                                                      If the file doesn't exist

  r            read (default)                                                                  FileNotFoundError

  w            write: overwrites (truncates) the file completely                              creates it

  a            append to the end                                                              creates it

  x            exclusive create                                                               creates it; FileExistsError if it exists

  r+           read and write, no truncation                                                   FileNotFoundError

 add b         binary: rb , wb for images, PDFs, .pkl model files                             same as above


           files.py (tested)


  with open("notes.txt", "w") as f:                            # 'with' closes the file automatically,
        f.write("line 1\n")                                    # even if an error happens inside the block
        f.writelines(["line 2\n"])


  with open("notes.txt", "a") as f:                            # append
        f.write("line 3\n")


  with open("notes.txt") as f:                                 # default mode "r"
        for line in f:                                         # memory-friendly: one line at a time
             print(line.strip())                               # line 1 / line 2 / line 3

--- PDF page 109 ---
with open("notes.txt") as f:
         text = f.read()                                   # whole file as ONE string
  # f.readline() -> next line;                 f.readlines() -> list of all lines


  try:
         open("missing.txt")
  except FileNotFoundError:
         print("No such file")




▸ JSON: the format every API speaks

           json_demo.py (course: Unit 2 Notes §3.6)


  import json


  order = {"id": 42, "items": ["samosa", "chai"], "paid": True, "note": None}


  text = json.dumps(order)                # dict -> JSON string: {"id": 42, ..., "paid": true, "note": null}
  back = json.loads(text)                 # JSON string -> dict               (s = "string")


  with open("order.json", "w") as f:
         json.dump(order, f, indent=2)                     # dict -> file
  with open("order.json") as f:
         data = json.load(f)                               # file -> dict



 JSON                   object          array            string            number                 true / false                null

 Python                 dict            list             str               int / float            True / False                None


This conversion is exactly what JsonResponse (2.11) and DRF serializers (2.16) do for you. A path that works
no matter where the server was started from is built with pathlib , as the course does for the ML model:
 Path(__file__).resolve().parent / "ml" / "iris_model.pkl" .


   ✏️ FILL IN THE BLANKS: SOCKETS AND FILES
    1. Server order: socket() →                           →                    →                 → recv()
    2. socket.SOCK_STREAM means the                               protocol; AF_INET means                           addresses.
    3. Strings must be converted with .                           () before send() .

    4. Mode that adds to the end of a file: "                         " ; mode to read a pickled model: "                         " .

    5. Python dict → JSON string: json.                           (d) ; JSON file → dict: json.                       (f) .

    6. Default port of runserver :                        ; PostgreSQL:                    .

   🔓 Answer key: 1) bind · listen · accept 2) TCP · IPv4 3) encode 4) a · rb 5) dumps · load 6) 8000 · 5432

--- PDF page 110 ---
2.6 Django from zero: MVT and the request cycle
📚 Sources: Unit 2 Notes §4.1, §4.3         LEC 4 (Python · Django) slides 15, 17   One-Shot Revision · Django MVT

 Complete Revision deck U2 slide 15


  🧠 START FROM ZERO
  Django is a free, open-source, high-level Python web framework for building secure, database-driven
  websites quickly. It is "batteries included": it ships with an ORM (talk to the database in Python), an auto‐
  matic admin panel, user authentication, forms, a template engine, URL routing, migrations and built-in
  protection against CSRF, XSS and SQL injection. It follows the DRY principle (Don't Repeat Yourself) and
  the MVT architecture. Instagram, Pinterest and Mozilla are well-known Django users.



▸ The three parts of MVT

  Part                  File                   Job                                                                           MVC equivalent

  Model                  models.py             the data: a Python class per table; fields = columns; the ORM                 Model
                                               turns it into SQL

  View                   views.py              the logic: a function/class that receives the request, talks to mod‐          Controller
                                               els and returns a response

  Template               templates/*           the presentation: HTML with {{ }} and {% %} placeholders                      View
                        .html

  (URL                   urls.py               maps each URL to a view                                                       part of the
  dispatcher)                                                                                                                controller


In MVT, Django itself is the controller: the framework receives the request, consults urls.py and calls your
view. So what MVC calls the "controller" is Django + your view, and MVC's "view" is Django's template. Keeping
data, logic and HTML in separate files is why MVT scales: a designer can edit templates without touching
Python, and the database can change without rewriting pages.


                                                                                                         models.py                     DB
                                                                                                         MODEL = data               SQLite / PG
                                                                                    3 ORM query
                                                                                                                        4 SQL / rows
                          1 request                       2 match path

         Browser                           urls.py                          views.py
           client                       URL dispatcher                     VIEW = logic

                                                                                                      5 context dict


                                                                                                           template
                                                                                                       TEMPLATE = HTML

                          7 HttpResponse travels back to the browser
                                                                                                                        6 rendered HTML


                    One request through Django's MVT (the course's five stops: browser, urls.py, views.py, models.py, template).

--- PDF page 111 ---
▸ Anatomy of one request, step by step

 1        Browser sends a request, e.g. GET /orders/7/ .

 2        Server hands it to Django: runserver in development, or gunicorn via wsgi.py in production.
          Django wraps it in an HttpRequest object and runs the middleware (sessions, CSRF, authentication:
          this is how request.user appears).

 3        URL dispatcher: ROOT_URLCONF (project urls.py ) is checked top to bottom; include() passes the
          rest to the app's urls.py ; <int:pk> captures 7.

 4        View runs: order_detail(request, pk=7) .

 5        Model / ORM: get_object_or_404(Order, pk=7) becomes SQL, and the row comes back as an
           Order object (or a 404).


 6        Template: render(request, "orders/detail.html", {"order": order}) fills the HTML.

 7        Response: an HttpResponse goes back through middleware to the browser, which displays it.


A view does not have to render a template: it can return a redirect or JSON instead, which is exactly what an
API endpoint does (2.11, 2.16).




     2.7 Project vs app: the full project structure
📚 Sources: Unit 2 Notes §4.2      LEC 4 (Python · Django) slide 16   LEC 5 (Django code-along) steps 3–4

 One-Shot Revision · Django MVT    Complete Revision deck U2 slide 15



  PROJECT                                                                APP

  One per website. Holds global configuration:                           One per feature (accounts, orders, enrollments,
     settings.py (installed apps, database, middle‐                      ml_app). Holds its own models, views, URLs and
  ware, templates) and the root URL table every re‐                      templates. A project usually contains many apps,
  quest reaches first. Created with django-admin                         and an app can be reused in other projects.
  startproject .                                                         Created with python manage.py startapp .


  ⚠️ COMMON MISTAKE
  An app does nothing until it is added to INSTALLED_APPS in settings.py . Until then Django will not find
  its models (no migrations) or its templates/ folder, and the error looks unrelated
  ("TemplateDoesNotExist", "no changes detected"). After changing INSTALLED_APPS , restart runserver
  (LEC 5 step 25 note).

--- PDF page 112 ---
▸ Key settings in settings.py

 Setting                     What it controls

  SECRET_KEY                 cryptographic signing (sessions, CSRF tokens). Keep it secret (env var in production).

  DEBUG                       True shows detailed error pages. Must be False in production.

  ALLOWED_HOSTS              domain names the site may serve when DEBUG=False .

  INSTALLED_APPS             built-in apps (admin, auth, contenttypes, sessions, messages, staticfiles) + yours +
                              "rest_framework" .

  MIDDLEWARE                 hooks run on every request/response: Security, Session, Common, Csrf, Authentication, Message,
                             XFrameOptions.

  ROOT_URLCONF               which urls.py is the root URL table ( "myproject.urls" ).

  TEMPLATES                  template engine; APP_DIRS: True = look in each app's templates/ ; DIRS = extra folders.

  DATABASES                  default SQLite file db.sqlite3 ; change to PostgreSQL in 2.15.

  STATIC_URL                 URL prefix for CSS/JS/images ( "static/" ).

  LOGIN_REDIRECT_UR          where to go after login (course: "dashboard" ).
 L



     PYQ     Re-Exam 2023-24 · Q4(a)                                                                                           10 M


  What is Django MVT? Explain the project structure of Django Framework.

     ✓   MODEL ANSWER: WRITE THIS


  1. DJANGO AND MVT (DEFINITION)

  Django is a high-level, open-source Python web framework that encourages rapid development and clean,
  pragmatic design ("batteries included": ORM, admin, authentication, forms, security). It follows the MVT
  (Model–View–Template) architectural pattern, which separates an application into three layers:

         Model ( models.py ): defines the data structure. Each model is a Python class subclassing
         models.Model ; each attribute is a database column. Django's ORM translates model operations into
         SQL, so the developer never writes SQL directly.
         View ( views.py ): contains the business logic. It receives an HttpRequest , fetches/updates data
         through models, and returns an HttpResponse (usually by rendering a template).
         Template ( templates/ ): the presentation layer, HTML with Django Template Language placeholders
         ( {{ variable }} , {% tag %} ) that the view fills with data.
         URL dispatcher ( urls.py ) maps each URL to a view. Django itself acts as the controller.

  Flow: Browser → urls.py → View → Model (database) → View → Template → HTML response →
  Browser. (Draw the diagram from 2.6.)

  MVT vs MVC: Django's View ≈ MVC's Controller and Django's Template ≈ MVC's View; the "controller" part
  is handled by the framework through URL routing.

--- PDF page 113 ---
2. PROJECT STRUCTURE
  Created by django-admin startproject myproject and python manage.py startapp myapp :

                project tree


     myproject/                          <- outer folder (just a container; can be renamed)
     ├── manage.py                       <- command-line utility for this project
     ├── db.sqlite3                      <- default SQLite database (created by first migrate)
     ├── myproject/                      <- inner folder = the PROJECT package (configuration)
     │     ├── __init__.py               <- marks the folder as a Python package
     │     ├── settings.py               <- all configuration
     │     ├── urls.py                   <- root URL table
     │     ├── asgi.py                   <- entry point for ASGI (async) servers
     │     └── wsgi.py                   <- entry point for WSGI servers (gunicorn) in production
     └── myapp/                          <- an APP = one feature
           ├── __init__.py
           ├── admin.py                  <- register models with the admin site
           ├── apps.py                   <- app configuration class (MyappConfig)
           ├── migrations/               <- migration files: version history of the DB schema
           │     └── __init__.py
           ├── models.py                 <- Model layer
           ├── tests.py                  <- unit tests
           ├── views.py                  <- View layer
           ├── urls.py                   <- app URL table (you create it)
           ├── templates/myapp/          <- Template layer (you create it)
           └── static/myapp/             <- CSS, JS, images (you create it)



    File                 Purpose

     manage.py           Runs project commands: runserver , startapp , makemigrations , migrate , create‐
                         superuser , shell . It sets DJANGO_SETTINGS_MODULE to this project's settings.

     settings.py          INSTALLED_APPS , MIDDLEWARE , DATABASES , TEMPLATES , STATIC_URL ,
                          SECRET_KEY , DEBUG , ALLOWED_HOSTS .

     urls.py              urlpatterns list; routes admin/ and include() s each app's URLs.
    (project)

     wsgi.py /           Interfaces between the web server and Django for deployment (sync / async).
     asgi.py

     models.py           Model classes → database tables.

     views.py            View functions/classes → responses.

     admin.py             admin.site.register(Model) to manage data in the admin panel.

     apps.py             App metadata; the app is activated by listing it in INSTALLED_APPS .

     migrations/         Files created by makemigrations and applied by migrate .

     tests.py            Automated tests run with python manage.py test .

--- PDF page 114 ---
File                   Purpose

     templates/ ,          HTML templates and static assets of the app.
     static/


  Project vs app: a project is the whole website (configuration plus the root URL table); an app is a reusable
  module for one feature. One project contains many apps.

  3. ADVANTAGES OF MVT
  Separation of concerns (designers and developers work independently), reusability of apps, rapid develop‐
  ment (admin, ORM, auth built in), security by default (CSRF, XSS, SQL injection protection), scalability and
  easy maintenance.

  🎯 Marking scheme guess: 2 M definition of Django + MVT · 2 M Model/View/Template roles + diagram · 1 M flow / MVC comparison · 4 M
  structure tree with each file explained · 1 M advantages




    2.8 Setting up a project, an app and the admin
📚 Sources: LEC 5 (Django code-along) steps 1–8         Lecture 5 Commands Reference steps 1–8     Unit 2 Notes §4.2, §4.4, §4.6



▸ The course's setup sequence (LEC 5 steps 1–8)

           terminal


  mkdir imap-lecture5 && cd imap-lecture5
  python -m venv venv                                        # isolated environment for this project
  source venv/bin/activate                                   # macOS / Linux
  # venv\Scripts\Activate.ps1                                # Windows PowerShell
  pip install django
  django-admin --version                                     # e.g. 5.0.6
  django-admin startproject mysite .                         # the "." = create it in the current folder
  python manage.py startapp accounts                         # one app = one feature
  # add "accounts" to INSTALLED_APPS in mysite/settings.py
  python manage.py migrate                                   # create built-in tables (auth, admin, sessions)
  python manage.py createsuperuser                           # admin login (username, email, password)
  python manage.py runserver                                 # http://127.0.0.1:8000/



Without the trailing dot, startproject mysite creates an extra outer folder mysite/ containing manage.py ,
and you must cd mysite first.


▸ manage.py commands you must know

 Command                                                         Does

  runserver [port]                                               start the development server (default 8000)

  startapp name                                                  create an app folder

--- PDF page 115 ---
Command                                             Does

  makemigrations [app]                               write migration files from model changes (does NOT touch the DB)

  migrate                                            apply pending migrations to the database

  showmigrations / sqlmigrate app 0001               list migrations / show the SQL a migration will run

  createsuperuser                                    create an admin user

  shell                                              Python shell with Django loaded (for ORM queries)

  dbshell                                            open the database's own SQL client

  collectstatic                                      copy static files to STATIC_ROOT for production

  test / check                                       run tests / check the project for problems

  drf_create_token user                              (DRF authtoken) create an API token for a user



▸ The admin site
Django generates a complete, password-protected admin interface at /admin/ where staff can create, read,
update and delete rows of any registered model. It is already switched on in a new project:
 "django.contrib.admin" is in INSTALLED_APPS and path("admin/", admin.site.urls) is in the root
 urls.py . To use it you only need to migrate , createsuperuser , and register your models in the app's
 admin.py . The admin labels each row using the model's __str__ .

           myapp/admin.py: two ways to register


  from django.contrib import admin
  from .models import Student


  # 1) simplest
  # admin.site.register(Student)


  # 2) with options (decorator form)
  @admin.register(Student)
  class StudentAdmin(admin.ModelAdmin):
        list_display = ("roll_no", "name", "email")         # columns in the list page
        search_fields = ("name", "roll_no")                 # search box
        list_filter = ("year",)                             # sidebar filter




   ✏️ COMMAND COMPLETION
    1. Create project myproject in the current folder:                    startproject myproject

    2. Create app: python manage.py                  myapp

    3. After editing models: python manage.py                    then python manage.py
    4. Admin login: python manage.py
    5. Open the ORM playground: python manage.py
    6. See the SQL of migration 0001 of myapp: python manage.py                            myapp 0001

    7. Activate a venv on macOS:                  venv/bin/activate

--- PDF page 116 ---
🔓 Answer key: 1) django-admin · . 2) startapp 3) makemigrations · migrate 4) createsuperuser 5) shell 6) sqlmigrate 7) source

   PYQ        Re-Exam 2023-24 · Q5(b)                                                                                              10 M


  What is Django? Write the steps for creating: 1. a new Django project "myproject" 2. an app "myapp"
  3. how to activate the Admin console 4. sample code to create a simple model and register it with
  Admin 5. sample code for creating a View.

   ✓       MODEL ANSWER: WRITE THIS

  Django is a free, open-source, high-level Python web framework for building secure, maintainable, data‐
  base-driven web applications rapidly. It follows the MVT (Model–View–Template) pattern and the DRY prin‐
  ciple and is "batteries included": ORM, automatic admin interface, authentication, URL routing, template
  engine, forms, migrations, and protection against CSRF, XSS and SQL injection.

  STEP 1: CREATE THE PROJECT "MYPROJECT"

               terminal


       python -m venv venv
       source venv/bin/activate                          # Windows: venv\Scripts\activate
       pip install django
       django-admin startproject myproject
       cd myproject                                      # folder that contains manage.py
       python manage.py runserver                        # check: http://127.0.0.1:8000/ shows the rocket page



  STEP 2: CREATE THE APP "MYAPP" AND REGISTER IT

               terminal + myproject/settings.py


       # $ python manage.py startapp myapp


       INSTALLED_APPS = [
             "django.contrib.admin",                     # admin, auth, contenttypes, sessions,
             "django.contrib.auth",                      # messages, staticfiles are already here
             # ...
             "myapp",                                    # <- add the new app
       ]



  STEP 3: ACTIVATE THE ADMIN CONSOLE
  The admin app is already in INSTALLED_APPS and routed in myproject/urls.py
  ( path("admin/", admin.site.urls) ). Create its tables and a login, then open it:

               terminal


       python manage.py migrate                          # creates auth, admin, session tables
       python manage.py createsuperuser                  # enter username, email, password

--- PDF page 117 ---
python manage.py runserver
     # open http://127.0.0.1:8000/admin/ and log in with the superuser



  STEP 4: A SIMPLE MODEL REGISTERED WITH ADMIN

              myapp/models.py


     from django.db import models


     class Student(models.Model):
           name = models.CharField(max_length=100)
           email = models.EmailField(unique=True)
           marks = models.IntegerField(default=0)
           joined = models.DateField(auto_now_add=True)


           def __str__(self):
                return self.name



              myapp/admin.py


     from django.contrib import admin
     from .models import Student


     admin.site.register(Student)



              terminal


     python manage.py makemigrations myapp    # creates myapp/migrations/0001_initial.py
     python manage.py migrate                 # creates table myapp_student
     # refresh /admin/ : "Students" now appears, with Add / Change / Delete



  STEP 5: A VIEW (WITH ITS URL)

              myapp/views.py


     from django.http import HttpResponse
     from django.shortcuts import render
     from .models import Student


     def home(request):                                          # simplest view
           return HttpResponse("Hello, welcome to myapp!")


     def student_list(request):                                  # view using model + template
           students = Student.objects.all()
           return render(request, "myapp/student_list.html", {"students": students})

--- PDF page 118 ---
myapp/urls.py (create this file)


     from django.urls import path
     from . import views


     urlpatterns = [
           path("", views.home, name="home"),
           path("students/", views.student_list, name="student-list"),
     ]



              myproject/urls.py


     from django.contrib import admin
     from django.urls import path, include


     urlpatterns = [
           path("admin/", admin.site.urls),
           path("", include("myapp.urls")),
     ]



              myapp/templates/myapp/student_list.html


     <h1>Students</h1>
     <ul>
         {% for s in students %}
           <li>{{ s.name }}: {{ s.marks }}</li>
         {% empty %}
           <li>No students yet.</li>
         {% endfor %}
     </ul>



  Run python manage.py runserver and visit / (text response) and /students/ (rendered list).

  🎯 Marking scheme guess: 2 M what is Django · 1 M project · 1 M app + INSTALLED_APPS · 2 M admin (migrate, createsuperuser,
  /admin/) · 2 M model + admin.register + migrations · 2 M view + URL wiring




    2.9 Models, fields, relationships and migrations
📚 Sources: Unit 2 Notes §4.4, §4.6      LEC 4 (Python · Django) slide 18       One-Shot Revision · Models, migrations & the ORM

 Complete Revision deck U2 slide 16

--- PDF page 119 ---
🧠 START FROM ZERO
  A model is a Python class that describes one database table. Class → table (named appname_modelname ,
  e.g. orders_order ); class attribute (field) → column; one object → one row. Django adds an auto-incre‐
  ment primary key id automatically. You never write CREATE TABLE : migrations do it.


           orders/models.py (course example: Unit 2 Notes §4.6)


  from django.db import models
  from django.contrib.auth.models import User


  class Order(models.Model):
         customer = models.ForeignKey(User, on_delete=models.CASCADE)                 # many orders -> one user
         item = models.CharField(max_length=100)
         quantity = models.IntegerField(default=1)
         price = models.DecimalField(max_digits=8, decimal_places=2)                  # exact: right for money
         paid = models.BooleanField(default=False)
         created_at = models.DateTimeField(auto_now_add=True)                         # set once, on creation


         def __str__(self):                             # label in admin and shell
             return f"{self.item} x {self.quantity}"




▸ Field types

 Field                              Stores / SQL type (roughly)       Required args / notes

  CharField                         short text, VARCHAR                max_length is required

  TextField                         long text, TEXT                   no limit

  IntegerField /                    whole numbers                     positive variant rejects negatives
  PositiveIntegerField

  FloatField                        approximate decimals              not for money

  DecimalField                      exact decimals, NUMERIC            max_digits , decimal_places required

  BooleanField                      True / False                      give a default

  DateField / DateTimeField         date / timestamp                   auto_now_add=True (on create),
                                                                       auto_now=True (on every save)

  EmailField , URLField ,           validated text                    CharField with built-in validators
  SlugField

  FileField / ImageField            file path; file saved to           upload_to
                                     MEDIA_ROOT

  ForeignKey                        many-to-one, FK column            target model + on_delete
                                     xxx_id

  OneToOneField                     one-to-one (unique FK)            e.g. one Profile per User

  ManyToManyField                   many-to-many via a hidden         optional through= model
                                    join table

--- PDF page 120 ---
▸ Field options

 Option                         Meaning

  null=True                     the database column may store NULL

  blank=True                    the form/validation allows an empty value

  default=...                   value used when none is given

  unique=True                   no two rows may share this value (UNIQUE index in the DB)

  choices=...                   restrict to a fixed list (shown as a dropdown in forms/admin)

  primary_key=True              use this field as PK instead of the automatic id

  validators=[...]              extra checks run during validation

  related_name="..."            name of the reverse accessor ( user.orders.all() instead of user.order_set.all() )



  ⚠️ COMMON MISTAKE
     null is about the database, blank is about forms. For an optional text field use blank=True only (Djan‐
  go stores "" ). For an optional number, date or FK use null=True, blank=True .
     on_delete=models.SET_NULL requires null=True .



▸ Relationships and on_delete

 Relationship       Field (put it on the "many" side for FK)            Example                     Reverse access

 One-to-many            ForeignKey(User, on_delete=...)                 many orders → one            user.order_set.all()
                                                                        user

 One-to-one             OneToOneField(User,                             one profile per user         user.profile
                    on_delete=...)

 Many-to-               ManyToManyField(Course)                         students ↔ courses           course.student_set.all(
 many                                                                                               )


  on_delete=                                    When the parent row is deleted…

  CASCADE                                       delete the child rows too (orders of a deleted user vanish)

  PROTECT                                       refuse to delete the parent while children exist ( ProtectedError )

  SET_NULL                                      keep children, set the FK to NULL (needs null=True )

  SET_DEFAULT / DO_NOTHING                      set the FK to its default / do nothing (DB may complain)


A many-to-many with extra data (an enrollment date, a grade) uses an explicit join model: two ForeignKeys in
a "through" model, optionally exposed as ManyToManyField(Course, through="Enrollment") . This is exactly
the 2025-26 Q7 case study (2.18).


▸ Migrations: from class to table

 Step       Command                                   What happens

 1          edit models.py                            write or change the class

--- PDF page 121 ---
Step      Command                           What happens

 2          python manage.py                 writes migrations/0001_initial.py describing the change. It does not
           makemigrations                    touch the DB.

 3          python manage.py migrate         applies pending migration files: runs CREATE TABLE / ALTER TABLE

 Result     orders_order                     the real table exists; sqlmigrate orders 0001 shows the SQL


Migrations are version control for the database schema: each change is a numbered file committed to Git
with the code, so the whole team (and the production server) can rebuild an identical schema. A model change
followed by neither command never reaches the real table.

     🚨 NOT IN YOUR STUDY MATERIAL · PART OF 6 MARKS · FINAL 2025-26 Q7(A)
     What's missing: how to declare uniqueness constraints and validation on models: unique=True ,
      unique_together / UniqueConstraint , validators, clean() . Q7(A) asks for them explicitly. Verdict:
     MUST LEARN (short, and it decides 1–2 marks in the case study).



▸ Uniqueness constraints and validation

           constraints_and_validation.py


  from django.core.exceptions import ValidationError
  from django.core.validators import MinValueValidator, MaxValueValidator, RegexValidator
  from django.db import models


  class Course(models.Model):
        code = models.CharField(max_length=10, unique=True,                        # 1) single-column unique
                                  validators=[RegexValidator(r"^[A-Z]{2,4}\d{3}$",
                                                                 "Use a code like CS101")])
        credits = models.PositiveSmallIntegerField(
             validators=[MinValueValidator(1), MaxValueValidator(6)])                # 2) value validators
        capacity = models.PositiveIntegerField(default=60)


  class Enrollment(models.Model):
        student = models.ForeignKey("Student", on_delete=models.CASCADE)
        course = models.ForeignKey(Course, on_delete=models.CASCADE)


        class Meta:
             constraints = [                                                         # 3) multi-column unique
                   models.UniqueConstraint(fields=["student", "course"],
                                           name="unique_student_course"),
             ]
             # older equivalent: unique_together = [("student", "course")]


        def clean(self):                                                             # 4) cross-field rule

--- PDF page 122 ---
if self.course_id and self.course.enrollment_set.count() >= self.course.capacity:
                   raise ValidationError("This course is full.")



 Tool                                         Enforced by                            Error raised                      When it runs

  unique=True ,                               the database (index/constraint,         IntegrityError on                always, at
  UniqueConstraint , unique_‐                 created by migrate) + model            save (DB);                        INSERT/UPDATE
 together , CheckConstraint                   validation                              ValidationError in
                                                                                     forms

  validators=[...] ,                          Python (Django)                         ValidationError                  only during full_‐
  max_length , choices                                                                                                 clean()

  clean() method                              Python, rules spanning several          ValidationError                  only during full_‐
                                              fields                                                                   clean()



  ⚠️ COMMON MISTAKE
    obj.save() and Model.objects.create() do not run validators or clean() . Only obj.full_clean()
  does, and a ModelForm's is_valid() and the admin call it for you. Database constraints are the last line
  of defence and always fire. (A CheckConstraint is written
    models.CheckConstraint(condition=models.Q(capacity__gte=1), name="cap_min_1") ; in Django 5.0
  and older the argument is check= .)


   ✏️ FILL IN THE BLANKS: A MODEL
               myapp/models.py


     from django.db import ______                                                                       # (1)


     class Book(models.______):                                                                       # (2)
           title = models.CharField(______=200)                                                       # (3)
           isbn = models.CharField(max_length=13, ______=True)                                        # (4) no duplicates
           price = models.DecimalField(max_digits=7, ______=2)                                        # (5)
           author = models.ForeignKey("Author", on_delete=models.______)                              # (6) delete books with
     author
           published = models.DateField(null=True, ______=True)                                       # (7) optional in forms


           def ______(self):                                                                          # (8) label in admin
                 return self.title
     # then:      python manage.py ______              and   python manage.py ______                  # (9)



   🔓 Answer key: (1) models · (2) Model · (3) max_length · (4) unique · (5) decimal_places · (6) CASCADE · (7) blank · (8) __str__ · (9)
   makemigrations · migrate

--- PDF page 123 ---
2.10 The ORM in the Django shell
📚 Sources: Unit 2 Notes §6.3       LEC 5 (Django code-along) step 12     Lecture 5 Commands Reference step 12

 One-Shot Revision · ORM      Complete Revision deck U2 slide 16


    🚨 NOT IN YOUR STUDY MATERIAL · 10 MARKS · FINAL 2024-25 Q3(B)
    What's missing: your files show only all() , get() , filter() , __gte and order_by . Q3(b) also
    needs bulk_create , descending order, __range , first() / last() , count() , aggregate() with
      Avg/Sum/Min/Max/Count , and values() / values_list() . Verdict: MUST LEARN. It is a full 10-mark
    question built entirely from these helpers, and they also power views and the case study.


The ORM (Object-Relational Mapper) lets you query the database with Python. Every model gets a manager
called objects . Most methods return a QuerySet, a lazy description of a query: no SQL runs until you loop
over it, count it, slice it or print it. That is why filters can be chained cheaply.

            terminal


  python manage.py shell
  >>> from myapp.models import Employee
  >>> from django.db.models import Avg, Sum, Max, Min, Count, Q, F
  >>> print(Employee.objects.filter(salary__gte=50000).query)                            # see the SQL (LEC 5 step 12)
  SELECT ... FROM "myapp_employee" WHERE "myapp_employee"."salary" >= 50000




▸ CRUD and the helpers you need

 Goal                   ORM                                                                                 SQL equivalent

 Insert one             Employee.objects.create(name="Asha", salary=55000)                                      INSERT INTO ...

 Insert (two            e = Employee(name="Ravi"); e.save()                                                     INSERT
 steps)

 Insert many            Employee.objects.bulk_create([e1, e2])                                              one multi-row INSERT

 All rows               Employee.objects.all()                                                                  SELECT *

 Exactly one            Employee.objects.get(id=1)                                                              WHERE id = 1

 Matching rows          filter(dept="IT") / exclude(dept="IT")                                                  WHERE / WHERE NOT

 Sort                   order_by("salary") , order_by("-salary")                                                ORDER BY salary
                                                                                                            [DESC]

 Range                  filter(salary__range=(40000, 60000))                                                    BETWEEN 40000 AND
                                                                                                            60000

 First / last           first() , last() (by pk if unordered)                                                   ORDER BY id LIMIT
                                                                                                            1

 Top N                  order_by("-salary")[:5]                                                                 LIMIT 5

 Count / exists         count() , exists()                                                                      COUNT(*)

 Aggregate              aggregate(Avg("salary"))                                                                SELECT AVG(salary)

--- PDF page 124 ---
Goal                   ORM                                                                                     SQL equivalent

 Group by               values("dept").annotate(n=Count("id"))                                                     GROUP BY dept

 Some columns           values("name", "salary") , values_list("name", flat=True)                                  SELECT name,
                                                                                                                salary

 Update                 e.salary = 60000; e.save() or                                                              UPDATE ... SET
                        filter(...).update(salary=F("salary") * 1.1)

 Delete                 e.delete() / filter(...).delete()                                                          DELETE FROM

 OR condition           filter(Q(dept="IT") | Q(salary__gt=70000))                                                 WHERE ... OR ...



▸ Field lookups (double underscore)
 exact , iexact · contains , icontains (case-insensitive LIKE) · startswith , endswith · gt , gte ,
 lt , lte · range · in=[...] · isnull=True · dates: joined__year=2025 · across relations:
 enrollment__course__code="CS101" .


  GET()                                                                       FILTER()

  Returns one object. Raises Model.DoesNotExist                               Returns a QuerySet (0, 1 or many rows), never
  if no row matches and                                                       raises for "no match" (just empty). Chainable:
   MultipleObjectsReturned if more than one                                   filter(...).exclude(...).order_by(...) .
  does. In views use get_object_or_404() .



   ✏️ COMPLETE THE ORM QUERIES
    1. Employees earning more than 50,000: Employee.objects.filter(salary                                            =50000)

    2. Highest paid first: Employee.objects.                             ("                salary")

    3. Average salary: Employee.objects.                              (Avg("salary")) → key '                          '

    4. Only names as a flat list: Employee.objects.values_list("name",                                        =True)

    5. Names containing "an", any case: filter(name                                  ="an")

    6. Top 3 salaries: Employee.objects.order_by("-salary")
    7. Number of HR employees: Employee.objects.filter(dept="HR").                                            ()


   🔓 Answer key: 1) __gt 2) order_by · - 3) aggregate · salary__avg 4) flat 5) __icontains 6) [:3] 7) count

   PYQ       Final 2024-25 · Q3(b)                                                                                                  10 M


  Write the code for creating an Employee model and answer the following using the Django shell: 1.
  create employees (insert) 2. retrieve all employees (select) 3. employees ordered by salary 4. filter
  employees by salary range 5. first and last employee 6. count of employees 7. aggregation on
  salaries 8. employees with selected fields.

   ✓    MODEL ANSWER: WRITE THIS

--- PDF page 125 ---
MODEL AND MIGRATION

              myapp/models.py


     from django.db import models


     class Employee(models.Model):
           name = models.CharField(max_length=100)
           email = models.EmailField(unique=True)
           department = models.CharField(max_length=50)
           salary = models.DecimalField(max_digits=10, decimal_places=2)
           joined_on = models.DateField(auto_now_add=True)


           def __str__(self):
                return self.name



              terminal


     python manage.py makemigrations myapp
     python manage.py migrate
     python manage.py shell



              Django shell


     >>> from myapp.models import Employee
     >>> from django.db.models import Avg, Sum, Max, Min, Count


     # 1. INSERT
     >>> Employee.objects.create(name="Asha", email="asha@corp.com", department="IT",
     salary=55000)
     <Employee: Asha>
     >>> e = Employee(name="Ravi", email="ravi@corp.com", department="HR", salary=42000)
     >>> e.save()
     >>> Employee.objects.bulk_create([
     ...        Employee(name="Meera", email="meera@corp.com", department="IT", salary=78000),
     ...        Employee(name="John", email="john@corp.com", department="Sales", salary=61000),
     ...        Employee(name="Sara", email="sara@corp.com", department="HR", salary=35000),
     ... ])
     [<Employee: Meera>, <Employee: John>, <Employee: Sara>]


     # 2. SELECT all
     >>> Employee.objects.all()
     <QuerySet [<Employee: Asha>, <Employee: Ravi>, <Employee: Meera>, <Employee: John>, <Employ‐
     ee: Sara>]>
     >>> for emp in Employee.objects.all():
     ...        print(emp.id, emp.name, emp.salary)

--- PDF page 126 ---
# 3. ORDER BY salary
     >>> Employee.objects.order_by("salary")              # ascending
     <QuerySet [<Employee: Sara>, <Employee: Ravi>, <Employee: Asha>, <Employee: John>, <Employee:
     Meera>]>
     >>> Employee.objects.order_by("-salary")             # descending
     <QuerySet [<Employee: Meera>, <Employee: John>, <Employee: Asha>, <Employee: Ravi>, <Employ‐
     ee: Sara>]>


     # 4. FILTER by salary range (inclusive, SQL BETWEEN)
     >>> Employee.objects.filter(salary__range=(40000, 60000))
     <QuerySet [<Employee: Asha>, <Employee: Ravi>]>
     >>> Employee.objects.filter(salary__gte=40000, salary__lte=60000)          # same result
     >>> Employee.objects.filter(salary__gt=60000)
     <QuerySet [<Employee: Meera>, <Employee: John>]>


     # 5. FIRST and LAST (by primary key when no ordering is given)
     >>> Employee.objects.first()
     <Employee: Asha>
     >>> Employee.objects.last()
     <Employee: Sara>
     >>> Employee.objects.order_by("salary").first()           # lowest-paid employee
     <Employee: Sara>


     # 6. COUNT
     >>> Employee.objects.count()
     5
     >>> Employee.objects.filter(department="IT").count()
     2


     # 7. AGGREGATION on salaries
     >>> Employee.objects.aggregate(Avg("salary"), Sum("salary"), Max("salary"), Min("salary"),
     Count("id"))
     {'salary__avg': Decimal('54200'), 'salary__sum': Decimal('271000'), 'salary__max':
     Decimal('78000'),
         'salary__min': Decimal('35000'), 'id__count': 5}
     >>> Employee.objects.aggregate(avg_salary=Avg("salary"))                # custom key
     {'avg_salary': Decimal('54200')}
     >>> Employee.objects.values("department").annotate(total=Sum("salary"))             # per department


     # 8. SELECTED fields only
     >>> Employee.objects.values("name", "salary")               # list of dicts
     <QuerySet [{'name': 'Asha', 'salary': Decimal('55000.00')}, {'name': 'Ravi', 'salary':
     Decimal('42000.00')}, ...]>
     >>> Employee.objects.values_list("name", "salary")          # list of tuples

--- PDF page 127 ---
>>> Employee.objects.values_list("name", flat=True)                        # flat list
       <QuerySet ['Asha', 'Ravi', 'Meera', 'John', 'Sara']>



  Notes: DecimalField values come back as Python Decimal objects (exact formatting differs slightly by
  database). aggregate() returns a plain dict, not a QuerySet. QuerySets are lazy and run SQL only when
  evaluated.

  🎯 Marking scheme guess: 2 M model + migrations · 1 M each for the eight queries (insert, all, order_by, range, first/last, count, aggregate,
  values)




   PYQ       Re-Exam 2023-24 · Q7(b)                                                                                                 10 M


  What are Django Models? How to insert and view records into a Django model "Employee" with
  fields "srno" and "name", stored in a database using Django ORM. Write the steps and code.

   ✓    MODEL ANSWER: WRITE THIS

  Django Models: a model is the single, definitive source of information about the data of an application. It is
  a Python class that subclasses django.db.models.Model . Each model maps to one database table, each
  attribute (field) to a column, and each instance to a row. Django's ORM converts operations on model ob‐
  jects into SQL, so the same code works on SQLite, PostgreSQL or MySQL. Django automatically adds an
    id primary key, creates the table through migrations, validates field types, supports relationships (For‐
  eignKey, OneToOne, ManyToMany) and can expose the model in the admin panel.

  STEP 1: PROJECT AND APP

              terminal


       django-admin startproject company
       cd company
       python manage.py startapp myapp
       # settings.py -> INSTALLED_APPS = [..., "myapp"]



  STEP 2: DEFINE THE MODEL

              myapp/models.py


       from django.db import models


       class Employee(models.Model):
            srno = models.IntegerField(unique=True)                        # serial number, no duplicates
            name = models.CharField(max_length=100)


            class Meta:
                ordering = ["srno"]                                        # default sort order

--- PDF page 128 ---
def __str__(self):
                return f"{self.srno} - {self.name}"



  (Alternative: srno = models.IntegerField(primary_key=True) makes srno itself the primary key instead
  of the automatic id .)

  STEP 3: CREATE THE TABLE

              terminal


     python manage.py makemigrations myapp         # writes myapp/migrations/0001_initial.py
     python manage.py migrate                      # CREATE TABLE "myapp_employee" (id, srno UNIQUE,
     name)



  STEP 4: INSERT RECORDS WITH THE ORM (DJANGO SHELL)

              python manage.py shell


     >>> from myapp.models import Employee
     >>> Employee.objects.create(srno=1, name="Asha")                     # way 1: create()
     <Employee: 1 - Asha>
     >>> e = Employee(srno=2, name="Ravi")                                # way 2: object + save()
     >>> e.save()
     >>> Employee.objects.bulk_create([Employee(srno=3, name="Meera"),
     ...                                    Employee(srno=4, name="John")])    # way 3: many at once



  STEP 5: VIEW (READ) RECORDS WITH THE ORM

              python manage.py shell


     >>> Employee.objects.all()
     <QuerySet [<Employee: 1 - Asha>, <Employee: 2 - Ravi>, <Employee: 3 - Meera>, <Employee: 4 -
     John>]>
     >>> for emp in Employee.objects.all():
     ...        print(emp.srno, emp.name)
     1 Asha
     2 Ravi
     3 Meera
     4 John
     >>> Employee.objects.get(srno=2)                         # exactly one
     <Employee: 2 - Ravi>
     >>> Employee.objects.filter(name__startswith="M")
     <QuerySet [<Employee: 3 - Meera>]>
     >>> Employee.objects.values("srno", "name")
     <QuerySet [{'srno': 1, 'name': 'Asha'}, {'srno': 2, 'name': 'Ravi'}, ...]>

--- PDF page 129 ---
STEP 6: VIEW THE RECORDS ON A WEB PAGE

              myapp/views.py + myapp/urls.py


     from django.shortcuts import render
     from .models import Employee


     def employee_list(request):
           employees = Employee.objects.all()                                  # ORM: SELECT * ... ORDER BY srno
           return render(request, "myapp/employees.html", {"employees": employees})


     # myapp/urls.py:        urlpatterns = [path("employees/", views.employee_list, name="employee-
     list")]
     # project urls.py: path("", include("myapp.urls"))



              myapp/templates/myapp/employees.html


     <table border="1">
        <tr><th>Sr No</th><th>Name</th></tr>
        {% for e in employees %}
           <tr><td>{{ e.srno }}</td><td>{{ e.name }}</td></tr>
        {% endfor %}
     </table>



  Records can also be inserted from a web form with a POST view that calls
    Employee.objects.create(...) and redirects (2.13), or from the admin panel. Optionally register the
  model ( admin.site.register(Employee) ) to insert and view rows from /admin/ too. Run
    python manage.py runserver and open /employees/ .


  🎯 Marking scheme guess: 2 M definition of models · 2 M model code · 1 M makemigrations/migrate · 2 M insert via ORM · 2 M view via
  ORM · 1 M view/template or admin




    2.11 Views, URLs and the three response types
📚 Sources: Unit 2 Notes §4.3, §4.7     LEC 5 (Django code-along) steps 6–7   Lecture 5 Commands Reference steps 6–7

 One-Shot Revision · Views, URLs & templates   Complete Revision deck U2 slide 17



▸ urls.py: the URL dispatcher

           orders/urls.py and myproject/urls.py (course: Unit 2 Notes §4.7)


  # orders/urls.py        (app level)
  from django.urls import path
  from . import views


  urlpatterns = [

--- PDF page 130 ---
path("", views.order_list, name="order-list"),                    # /orders/
         path("<int:pk>/", views.order_detail, name="order-detail"),        # /orders/7/
  ]


  # myproject/urls.py     (project level = ROOT_URLCONF)
  from django.contrib import admin
  from django.urls import path, include


  urlpatterns = [
         path("admin/", admin.site.urls),
         path("orders/", include("orders.urls")),         # hand everything under orders/ to the app
  ]



      path(route, view, name=...) : Django tests patterns top to bottom and calls the first match; no match
      gives a 404.
      Path converters capture parts of the URL and pass them as keyword arguments: <int:pk> (digits → int),
      <str:name> (default, no slash), <slug:slug> , <uuid:id> , <path:p> . /orders/7/ calls
      order_detail(request, pk=7) .

      name= lets you build URLs by name: {% url 'order-detail' order.id %} in templates,
      redirect("order-list") or reverse("order-list") in Python. Change the path in one place only.


▸ Writing views

           orders/views.py (course: Unit 2 Notes §4.7, One-Shot)


  from django.shortcuts import render, get_object_or_404, redirect
  from .models import Order


  def order_list(request):
         orders = Order.objects.filter(paid=False)
         return render(request, "orders/list.html", {"orders": orders})      # context keys = template
  vars


  def order_detail(request, pk):
         order = get_object_or_404(Order, pk=pk)         # 404 page instead of a crash
         return render(request, "orders/detail.html", {"order": order})


  def order_create(request):
         if request.method == "POST":                    # one view handles GET (show) and POST (save)
             Order.objects.create(item=request.POST["item"], price=request.POST["price"],
                                  customer=request.user)
             return redirect("order-list")               # redirect after POST: refresh won't resubmit
         return render(request, "orders/form.html")

--- PDF page 131 ---
request.                                  Holds

  method                                     "GET" , "POST" , …

  GET / POST                                query-string / form data (dict-like QueryDict ; use .get("k") to avoid a KeyError)

  user                                      the logged-in User or AnonymousUser (from AuthenticationMiddleware)

  session                                   dict-like per-browser storage (2.14)

  FILES , path , headers , body             uploads, URL path, HTTP headers, raw body


Views can also be class-based ( ListView , DetailView , LoginView ), wired with .as_view() , as in the
course's auth_views.LoginView.as_view(template_name="index.html") . Decorators restrict views:
 @login_required , @require_POST , @require_http_methods(["GET", "POST"]) .


    🚨 NOT IN YOUR STUDY MATERIAL · PART OF 4 MARKS · FINAL 2025-26 Q1(D)
    What's missing: render() is covered, but HttpResponse and JsonResponse are never explained, and
    Q1(d) asks you to contrast all three. Verdict: learn. It takes 5 minutes, it is guaranteed marks, and you
    need it for the SPA-vs-RSC question in Unit 4.



▸ render vs HttpResponse vs JsonResponse

           myapp/views.py: one view per response type


  from django.http import HttpResponse, JsonResponse
  from django.shortcuts import render
  from .models import Employee


  def hello(request):                                                     # raw text/HTML you write yourself
         return HttpResponse("Hello, world!")                             # status=200, content_type="text/html"


  def employee_page(request):                                             # HTML page from a template
         return render(request, "myapp/employees.html",
                          {"employees": Employee.objects.all()})


  def employee_api(request):                                              # JSON for JavaScript / React / mobile
         data = list(Employee.objects.values("id", "name"))                   # QuerySet -> list of dicts
         return JsonResponse({"employees": data})                         # Content-Type: application/json



                                                     render(request, tpl,
                   HttpResponse("...")                                                   JsonResponse({...})
                                                    ctx)

  Import           django.http                       django.shortcuts                    django.http

  Body            exactly the string/bytes you      a template filled with the          the dict serialised to JSON
                  pass                              context

  Content-         text/html (changeable)            text/html                           application/json
  Type

--- PDF page 132 ---
render(request, tpl,
                    HttpResponse("...")                                                           JsonResponse({...})
                                                        ctx)

  Returns         HttpResponse                          an HttpResponse (shortcut)              a subclass of HttpResponse

  Use for         simple text, quick tests,             normal web pages (MVT)                  APIs, AJAX/fetch, SPAs (React)
                  CSV/files, custom status

  Gotcha          no templating, HTML in                needs the template to exist in          non-dict data needs safe=False ;
                  Python is messy                       an app's templates/                     QuerySets must be converted to lists


Other shortcuts: redirect("name") returns a 302 redirect; get_object_or_404() raises Http404 . For a full
REST API use DRF's Response (2.16), which adds content negotiation, validation and status codes.


   ✏️ FILL IN THE BLANKS: URLS AND VIEWS
               blog/urls.py + blog/views.py


       from django.urls import ______                                                            # (1)
       from . import views
       urlpatterns = [
             path("posts/<______:pk>/", views.post_detail, ______="post-detail"),                                # (2) (3)
       ]


       from django.shortcuts import render, ______                                               # (4)
       from django.http import ______                                                            # (5)
       def post_detail(request, ______):                                                         # (6)
             post = get_object_or_404(Post, pk=pk)
             if request.headers.get("Accept") == "application/json":
                 return ______({"title": post.title})                                            # (7)
             return render(request, "blog/detail.html", {"post": ______})                            # (8)
       # project urls.py:         path("blog/", ______("blog.urls"))                            # (9)



   🔓 Answer key: (1) path · (2) int · (3) name · (4) get_object_or_404 · (5) JsonResponse · (6) pk · (7) JsonResponse · (8) post · (9) include

   PYQ        Final 2025-26 · Q1(d)   ★ LATEST                                                                                          4M


  What does urls.py do? Contrast returning render(request, ...) vs HttpResponse("...") vs
  JsonResponse({...}) in 2–3 lines each.

   ✓       MODEL ANSWER: WRITE THIS

  urls.py is Django's URL dispatcher (URLconf). It defines urlpatterns , a list of path() entries mapping
  URL patterns to view functions. For each request Django checks the patterns in order, captures path para‐
  meters (e.g. <int:id> ) and calls the matching view with them; if nothing matches it returns 404. The
  project urls.py uses include() to delegate to each app's urls.py , and name= allows reverse lookup
  with {% url %} / redirect() .

--- PDF page 133 ---
urls.py


     urlpatterns = [path("students/<int:id>/", views.student_detail, name="student-detail")]



        render(request, "page.html", context) : loads a template, fills it with the context dictionary and re‐
       turns an HttpResponse containing the generated HTML. Used for normal web pages in the MVT flow.
        HttpResponse("...") : the basic response class. It sends exactly the string you give as the body (de‐
       fault text/html ), with no template involved. Used for simple text, testing, or custom content types and
       status codes.
        JsonResponse({...}) : a subclass of HttpResponse that converts a Python dict to JSON and sets
        Content-Type: application/json . Used for APIs and AJAX/React front ends (lists need
        safe=False ).


  🎯 Marking scheme guess: 1 M urls.py role · 1 M each for the three responses (what it returns + when to use)


    2.12 Templates: DTL, inheritance, static, CSRF
📚 Sources: Unit 2 Notes §4.5      LEC 4 (Python · Django) slide 19    One-Shot Revision · template language

 Complete Revision deck U2 slide 17


A Django template is HTML plus the Django Template Language (DTL): {{ variable }} prints a value from
the view's context, and {% tag %} adds light logic. Templates can display and branch on data but can never
run arbitrary Python. This keeps logic in views and presentation in templates, enforced by the framework.

 Syntax                      Purpose                                            Example

  {{ var }}                  print a value (dot lookup works for attributes,     {{ user.username }} , {{ order.item }}
                             dict keys, list indexes, no-arg methods)

  {{ var|filter }}           transform a value                                   |length , |date:"d M Y" , |default:"-" ,
                                                                                 |upper , |truncatechars:30 , |floatfor‐
                                                                                mat:2

  {% if %}                   condition ( elif , else , endif )                   {% if user.is_authenticated %}

  {% for %}                  loop, with {% empty %} for no items;                {% for o in orders %}…{% endfor %}
                               forloop.counter

  {% url %}                  build a URL from its name                           {% url 'order-detail' o.id %}

  {% csrf_token %}           hidden anti-forgery field in every POST form       inside <form method="post">

  {% extends %} /            template inheritance                                {% extends "base.html" %}
  {% block %}

  {% include %}              insert another template                             {% include "nav.html" %}

  {% load static             link CSS/JS/images                                  {% static 'css/style.css' %}
 %} / {% static %}

  {# … #}                    comment (not sent to the browser)

--- PDF page 134 ---
▸ Template inheritance

           templates/base.html: the shared layout, written once


  {% load static %}
  <!DOCTYPE html>
  <html>
  <head>
     <title>{% block title %}My Site{% endblock %}</title>
     <link rel="stylesheet" href="{% static 'css/style.css' %}">
  </head>
  <body>
     <nav>Home | Orders</nav>
     {% block content %}{% endblock %}
  </body>
  </html>



           orders/templates/orders/list.html: a child page fills the blocks


  {% extends "base.html" %}
  {% block title %}Orders{% endblock %}
  {% block content %}
     <h1>Hi {{ user.username }}</h1>
     {% if orders %}
        <p>{{ orders|length }} unpaid</p>
        <ul>
        {% for o in orders %}
           <li><a href="{% url 'order-detail' o.id %}">{{ o.item }}</a> {{ o.created_at|date:"d M Y"
  }}</li>
        {% endfor %}
        </ul>
     {% else %}
        <p>No orders.</p>
     {% endif %}
  {% endblock %}



The base defines the shared layout once with named {% block %} s; every page starts with
 {% extends "base.html" %} and fills only the blocks it needs (DRY).


▸ Where templates and static files live
    Templates: myapp/templates/myapp/page.html (found automatically because
     TEMPLATES["APP_DIRS"] = True ; the inner myapp/ folder avoids name clashes between apps). Project-
    wide templates go in a folder listed in TEMPLATES["DIRS"] , e.g. BASE_DIR / "templates" .
    Static files (CSS, JS, images): myapp/static/myapp/style.css , served at STATIC_URL = "static/" .
    Write {% load static %} once per template. In production run collectstatic into STATIC_ROOT

--- PDF page 135 ---
(served by WhiteNoise or Nginx).
    Auto-escaping: {{ }} escapes < , > , & , quotes, which blocks XSS (a user named <script> is shown
    as text). |safe turns this off. Use it only on trusted HTML.

  ✍️ WHAT MUST NOT GO IN A TEMPLATE
  Business rules (capacity checks, prices, permissions logic), database queries or anything that changes
  data, complex calculations, secrets. Templates receive ready-made data from the view through the context
  dictionary of render() and only display it. This point is worth marks in 2025-26 Q7(C).


   ✏️ FILL IN THE BLANKS: TEMPLATE TAG S
               courses.html


      {% ______ "base.html" %}                                                        <!-- (1) -->
      {% block ______ %}                                                             <!-- (2) -->
      <ul>
           {% ______ c in courses %}                                                  <!-- (3) -->
            <li>{{ forloop.______ }}. {{ c.title|______ }}</li> <!-- (4) 1,2,3...                                       (5) CAPITALS -->
           {% ______ %}                                                               <!-- (6) shown when the list is empty -
      ->
            <li>No courses</li>
           {% endfor %}
      </ul>
      <form method="post" action="{% ______ 'enroll' student.id %}">                                   <!-- (7) -->
           {% ______ %}                                                               <!-- (8) -->
           <button>Enroll</button>
      </form>
      {% endblock %}



   🔓 Answer key: (1) extends · (2) content · (3) for · (4) counter · (5) upper · (6) empty · (7) url · (8) csrf_token


    2.13 Django forms and POST handling
📚 Sources: Unit 2 Notes §3.3, §4.7 (GET vs POST, redirect), §5.3 (CSRF)           One-Shot Revision · order_create

 LEC 5 (Django code-along) steps 24–25 (CSRF in fetch)        Not in your files: Django Form classes (added from standard references)



    🚨 NOT IN YOUR STUDY MATERIAL · NEEDED FOR 10 M FINAL 2024-25 Q7(A) + 10 M FINAL
      2025-26 Q7(B, D)

    What's missing: your files submit data either with raw request.POST["item"] or with a DRF serializer.
    Django's own forms.Form / ModelForm , is_valid() , cleaned_data and errors are never shown,
    yet 2024-25 Q7(a) asks for "a Django form for user input" (with from django import forms in its import
    table) and 2025-26 Q7 asks for form validation in the enroll flow. Verdict: MUST LEARN.

--- PDF page 136 ---
A Django form is a class that (1) renders HTML inputs, (2) validates submitted data, (3) converts it to Python
types ( "5.1" → 5.1 ) in cleaned_data , and (4) produces error messages to show back to the user. It re‐
places fragile code like float(request.POST["x"]) , which crashes on bad input.


  FORMS.FORM                                                 FORMS.MODELFORM
  Fields declared by hand. Not tied to a table. Use          Fields generated from a model ( class Meta:
  for search boxes, contact forms, login, ML inputs          model, fields ). Runs model validation too
  (Iris). You decide what to do with cleaned_data .          (unique, validators, clean() ), and form.save()
                                                             INSERTs/UPDATEs the row.


           myapp/forms.py


  from django import forms
  from .models import Employee


  class ContactForm(forms.Form):                                  # plain form
        name = forms.CharField(max_length=100)
        email = forms.EmailField()                                # format checked automatically
        age = forms.IntegerField(min_value=18, max_value=60)
        message = forms.CharField(widget=forms.Textarea, required=False)
        # one-field rule: def clean_name(self): ... raise forms.ValidationError("...")


  class EmployeeForm(forms.ModelForm):                            # form built from the model
        class Meta:
             model = Employee
             fields = ["name", "email", "department", "salary"]


        def clean(self):                                          # rule across SEVERAL fields
             cleaned = super().clean()
             if cleaned.get("department") == "Intern" and (cleaned.get("salary") or 0) > 30000:
                   raise forms.ValidationError("Intern salary cannot exceed 30,000.")
             return cleaned




▸ The standard form view (memorise this shape)

           myapp/views.py


  from django.contrib import messages
  from django.shortcuts import render, redirect
  from .forms import EmployeeForm


  def add_employee(request):
        if request.method == "POST":
             form = EmployeeForm(request.POST)           # 1. BIND the submitted data
             if form.is_valid():                         # 2. VALIDATE (fills cleaned_data or errors)
                   form.save()                           # 3. ACT: INSERT the row (ModelForm)

--- PDF page 137 ---
messages.success(request, "Employee added.")
                   return redirect("employee-list")        # 4. REDIRECT (Post/Redirect/Get)
        else:
             form = EmployeeForm()                         # GET: an empty, unbound form
        # GET, or invalid POST: re-render the page; the form now carries its errors
        return render(request, "myapp/employee_form.html", {"form": form})



With a plain forms.Form , step 3 uses the cleaned data yourself, e.g.
 Employee.objects.create(**form.cleaned_data) (the ** unpacking from 2.1).

 Form API                               What it gives

  Form(request.POST) / Form()           bound form (has data) / unbound form (empty)

  form.is_valid()                       runs field checks, clean_<field>() , clean() (and model validation for
                                        ModelForm); returns True/False

  form.cleaned_data                     dict of validated, type-converted values (only after is_valid() )

  form.errors / form.non_field‐         per-field errors / errors raised in clean()
 _errors()

  form.save()                           ModelForm only: saves and returns the model instance

  {{ form.as_p }}                       renders every field as <p> with labels and errors (also as_div , as_table )


           myapp/templates/myapp/employee_form.html


  <form method="post">
     {% csrf_token %}
     {{ form.non_field_errors }}
     {% for field in form %}
        <p>{{ field.label_tag }} {{ field }} {{ field.errors }}</p>                   <!-- or simply {{ form.as_p }}
  -->
     {% endfor %}
     <button type="submit">Save</button>
  </form>




▸ CSRF protection
CSRF (Cross-Site Request Forgery): a malicious site makes your logged-in browser send a POST to your site;
the browser attaches your cookies automatically, so the request looks genuine. Django's defence: it sets a se‐
cret token in the csrftoken cookie, {% csrf_token %} puts the same token in a hidden field
( csrfmiddlewaretoken ), and CsrfViewMiddleware rejects any POST/PUT/PATCH/DELETE whose token is
missing or wrong with 403 Forbidden. The attacker's page cannot read your token, so the forged request fails.
JavaScript fetch sends it as an X-CSRFToken header instead (the course's Iris page, LEC 5 step 25). API
clients authenticated by token (no cookies) do not need it.

--- PDF page 138 ---
▸ Post / Redirect / Get (PRG)

          POST /employees/add/                    view saves                          302 redirect                  GET /employees/
              form submitted
                                        →       is_valid() + save()
                                                                         →      Location: /employees/
                                                                                                             →         browser follows
                                                                                                                                            →

                                                                      200 list page


After a successful POST that changes data, return a redirect() instead of rendering a page. Refreshing then
repeats only the harmless GET, so the form is never submitted twice (no duplicate orders or enrollments), and
the result page has a proper bookmarkable URL. On an invalid POST, re-render the form (no redirect) so the
user sees the errors and keeps the typed values.


   ✏️ FILL IN THE BLANKS: A FORM VIEW
               contact view


     def contact(request):
            if request.______ == "POST":                                               # (1)
                 form = ContactForm(request.______)                                   # (2)
                 if form.______():                                                    # (3)
                        name = form.______["name"]                                    # (4)
                        send_thanks(name)
                        return ______("thanks")                                       # (5) PRG
            else:
                 form = ______()                                                      # (6)
            return render(request, "contact.html", {"form": ______})                                 # (7)
     # template:         <form method="post"> {% ______ %} {{ form.as_p }} ...                                        (8)



   🔓 Answer key: (1) method · (2) POST · (3) is_valid · (4) cleaned_data · (5) redirect · (6) ContactForm · (7) form · (8) csrf_token


    2.14 Authentication, authorization and sessions
📚 Sources: Unit 2 Notes §5.1–5.3        LEC 4 (Python · Django) slides 21–23          LEC 5 (Django code-along) steps 4–8

 Lecture 5 Commands Reference steps 4–8         One-Shot Revision · Auth & sessions           Complete Revision deck U2 slide 18


                    Authentication                                       Authorization

  Question          Who are you?                                         What are you allowed to do?

  Django             authenticate() , login() , lo‐                       @login_required , @permission_required ,
  tools             gout() , sessions, tokens                             has_perm() , groups, is_staff , DRF permission classes

  Failure           redirect to login / 401                              403 Forbidden

--- PDF page 139 ---
▸ django.contrib.auth out of the box
The built-in User model has username , email , password (always hashed, by default PBKDF2-SHA256, nev‐
er plain text), first_name , last_name and three flags: is_active , is_staff (may use admin),
 is_superuser (all permissions). Create users with
 User.objects.create_user(username, email, password) , never User(...) , because only create_user
hashes the password.

           accounts/views.py: a hand-written login (course: Unit 2 Notes §5.1)


  from django.contrib import messages
  from django.contrib.auth import authenticate, login, logout
  from django.contrib.auth.decorators import login_required
  from django.shortcuts import render, redirect


  def login_view(request):
        if request.method == "POST":
             user = authenticate(request, username=request.POST["username"],
                                   password=request.POST["password"])      # User or None
             if user is not None:
                   login(request, user)       # writes a session row + sets the sessionid cookie
                   return redirect("dashboard")
             messages.error(request, "Invalid username or password")
        return render(request, "index.html")


  def logout_view(request):
        logout(request)                        # clears the session: next request is anonymous
        return redirect("login")


  @login_required                             # anonymous users are redirected to LOGIN_URL
  def dashboard(request):
        return render(request, "dashboard.html")



The course uses Django's ready-made views instead (LEC 5 steps 5–7):

           mysite/settings.py + mysite/urls.py (LEC 5 steps 5–6)


  # settings.py
  LOGIN_REDIRECT_URL = "dashboard"          # where to go after a successful login
  LOGOUT_REDIRECT_URL = "login"


  # urls.py
  from django.contrib import admin
  from django.urls import path, include
  from django.contrib.auth import views as auth_views
  from accounts import views


  urlpatterns = [

--- PDF page 140 ---
path("admin/", admin.site.urls),
        path("accounts/login/", auth_views.LoginView.as_view(template_name="index.html"),
  name="login"),
        path("accounts/", include("django.contrib.auth.urls")),                    # logout/, password_change/, ...
        path("dashboard/", views.dashboard, name="dashboard"),
  ]



  ⚠️ COMMON MISTAKES
  (1) Forgetting LOGIN_REDIRECT_URL sends you to a page that doesn't exist after login, giving a 404 (LEC 5
  step 5). (2) Forgetting an import ( admin , path , auth_views , views ) is "the #1 NameError" (step 6). (3)
  Since Django 5.0, LogoutView accepts only POST, so log out with a small form containing
    {% csrf_token %} , not a plain link.



▸ Permissions, groups and decorators

 Tool                                       Effect                                                                 Where

  @login_required                           redirects anonymous users to the login page                            views.py

  @permission_required("app.‐               blocks the view unless the user holds the permission ( raise_ex‐       views.py
 codename")                                 ception=True → 403)

  request.user.is_authenticat‐              True once logged in                                                    views and
 ed                                                                                                                templates

  request.user.has_perm("app.‐              check one permission in code                                           views.py
 codename")

  LoginRequiredMixin                        same as @login_required for class-based views                          views.py


For every model Django auto-creates four permissions: add_ , change_ , delete_ , view_ + model name
(e.g. "myapp.change_employee" ). Permissions are normally bundled into a Group ("editors", "support staff")
and users are added to groups rather than given permissions one by one.

In templates: {% if user.is_authenticated %} and {% if perms.myapp.delete_employee %} show or hide
links and buttons.


▸ What a session actually is
HTTP is stateless: every request arrives as if from a stranger. A session is how Django recognises the same
browser across requests. Only a random session ID travels in a cookie; the real data stays on the server in the
 django_session table ( session_key , session_data , expire_date ).


                        Browser
              cookie: sessionid=8k3j…f91
                                           ⇄
                                           every request
                                                           SessionMiddleware
                                                             looks up the key
                                                                                   →
                                                                                          django_session table
                                                                                             key · data · expiry
                                                                                                                      →

                                                  request.session / request.user

--- PDF page 141 ---
login() writes the user's id into a new session row (rotating the key to prevent session fixation) and sets one
cookie; every later request carries the cookie back, so Django knows the user without the password ever travel‐
ling again. SESSION_COOKIE_AGE sets expiry (default 1,209,600 s = 2 weeks);
 SESSION_EXPIRE_AT_BROWSER_CLOSE = True ends it with the browser. Sessions can also be stored in cache,
files or signed cookies ( SESSION_ENGINE ), but the database is the default.

            using request.session like a dict


  from django.http import HttpResponse
  from django.shortcuts import redirect


  def visit_counter(request):
         count = request.session.get("visits", 0) + 1
         request.session["visits"] = count                                        # saved to django_session automatically
         return HttpResponse(f"You have visited {count} times")


  def add_to_cart(request, product_id):
         cart = request.session.get("cart", [])
         cart.append(product_id)                                                 # mutating the list alone is NOT detected...
         request.session["cart"] = cart                                          # ...so reassign it (or set session.modified
  = True)
         return redirect("cart")



                  Cookie                                                           Session

 Stored           in the browser                                                   on the server (DB), only the ID in a cookie

 Size             about 4 KB                                                       practically unlimited

 Security         user can read/edit it                                            user sees only a random key

 Use              preferences, the session ID, CSRF token                          logged-in user, cart, multi-step form data


Sessions also make CSRF protection possible (2.13). A browser stays logged in with the session cookie, while a
mobile app or script uses a token instead (2.16).




    2.15 Database connectivity: SQLite, PostgreSQL, raw SQL
📚 Sources: Unit 2 Notes §6.1–6.4          LEC 5 (Django code-along) steps 9–12     Lecture 5 Commands Reference steps 9–12

 One-Shot Revision · PostgreSQL connection        Complete Revision deck U2 slide 16


                                      SQLite                                                        PostgreSQL

 Where it lives                       one file, db.sqlite3 , next to manage.py                      a separate server process, port 5432

 Setup                                none: Django's default                                        a running server + driver + settings

 Many users writing at once           weak (locks the whole file)                                   strong, built for it

 Typical use                          learning, prototypes                                          production applications

--- PDF page 142 ---
Because Django talks to the database only through the ORM, switching is a configuration change, not a re‐
write: models, views and templates stay identical.

            terminal (LEC 5 steps 9–11)


  pip install psycopg2-binary djangorestframework             # psycopg2 = the Python driver for Postgres
  docker run --name imap-postgres \
        -e POSTGRES_PASSWORD=yourpassword \
        -e POSTGRES_DB=imapdb \
        -p 5432:5432 -d postgres:16                               # next time: docker start imap-postgres
  python manage.py migrate                                        # every table rebuilt inside Postgres
  python manage.py createsuperuser



            mysite/settings.py


  import os


  DATABASES = {
        "default": {
             "ENGINE": "django.db.backends.postgresql",              # sqlite3 / mysql / oracle also exist
             "NAME": "imapdb",                                       # database inside the server
             "USER": "postgres",
             "PASSWORD": os.environ.get("DB_PASSWORD", "yourpassword"),           # never commit the real one
             "HOST": "localhost",                                    # becomes "db" inside Docker Compose
  (Unit 5)
             "PORT": "5432",
        }
  }
  # SQLite default for comparison:
  # DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR /
  "db.sqlite3"}}



Useful extras: python manage.py dbshell opens psql ; python manage.py inspectdb generates model
classes from an existing database; print(qs.query) shows the SQL the ORM writes (LEC 5 step 12).


▸ Raw SQL, and why placeholders matter

            raw SQL done safely (Unit 2 Notes §6.4)


  from django.db import connection


  with connection.cursor() as cursor:
        cursor.execute("SELECT username FROM auth_user WHERE id = %s", [user_id])              # %s placeholder
        row = cursor.fetchone()

--- PDF page 143 ---
# or get model objects back:
  rich = Employee.objects.raw("SELECT * FROM myapp_employee WHERE salary > %s", [50000])



           SQL injection: what placeholders prevent


  name = request.GET["name"]                            # attacker types:           ' OR '1'='1
  # BAD: input glued into the SQL string
  cursor.execute(f"SELECT * FROM auth_user WHERE username = '{name}'")
  #     runs: SELECT * FROM auth_user WHERE username = '' OR '1'='1'                               -> returns EVERY user
  # GOOD: value passed separately; the driver escapes it
  cursor.execute("SELECT * FROM auth_user WHERE username = %s", [name])



The ORM always uses placeholders, which is one of the strongest reasons to prefer it. When several writes must
succeed or fail together (ACID atomicity, Unit 3), wrap them in with transaction.atomic(): . The case study
in 2.18 does this. How the ORM maps to SQL vs NoSQL (MongoDB) is Final 2025-26 Q5(B), answered in the
Unit 3 chapter ("ORM with SQL vs NoSQL").




      2.16 Django REST Framework
📚 Sources: Unit 2 Notes §7.1–7.5        LEC 5 (Django code-along) steps 13–16       Lecture 5 Commands Reference steps 13–16

 One-Shot Revision · DRF    Complete Revision deck U2 slide 19


                            HTML views (2.11)                   API views (DRF)

 Returns                    a rendered HTML page                JSON data

 Used by                    a browser                           any client: React (Unit 4), mobile app, another server, a script

 Staying logged in          session cookie                      a token sent with every request


A REST API organises URLs around resources (nouns) and lets the HTTP method say what to do. It is stateless
(each request carries its own credentials) and speaks JSON with proper status codes. Django REST
Framework (DRF) adds three ideas on top of Django:

           Client
   Postman · React · curl
                            →
                                        Router
                                   writes the URLs
                                                            →
                                                                  ViewSet
                                                                 CRUD logic
                                                                                 ⇄       model
                                                                                                  Serializer
                                                                                                 ⇄ JSON + validation    ⇄          Model / DB



                                                                     Response
                                                            →       JSON + status



 URL (router-generated)                          GET            POST                 PUT            PATCH                   DELETE

  /api/employees/                                list           create (201)

  /api/employees/<id>/                           retrieve                            update         partial_update          destroy (204)

--- PDF page 144 ---
▸ 1. Serializer: the translator

           accounts/serializers.py (LEC 5 step 13)


  from rest_framework import serializers
  from django.contrib.auth.models import User


  class UserSerializer(serializers.ModelSerializer):
        class Meta:
             model = User
             fields = ["id", "username", "email"]         # the hashed password can never leak



It works both ways: out, model object → dict → JSON ( serializer.data ); in, JSON → validated data
( is_valid() , validated_data , errors ) → save() . Bad input (missing field, malformed email) is rejected
with a 400 and a clear message before it touches the database. A ModelSerializer builds its fields from the
model; a plain Serializer declares them by hand (used for the ML input, 2.17). To see what DRF automates,
here is the same Create + Read written by hand:

           function-based API view (what a ModelViewSet does for you)


  from rest_framework import status
  from rest_framework.decorators import api_view
  from rest_framework.response import Response


  @api_view(["GET", "POST"])
  def employee_list(request):
        if request.method == "GET":                                      # READ
             serializer = EmployeeSerializer(Employee.objects.all(), many=True)
             return Response(serializer.data)                            # 200 + JSON list
        serializer = EmployeeSerializer(data=request.data)               # CREATE
        if serializer.is_valid():
             serializer.save()                                           # INSERT
             return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)




▸ 2. ViewSet and 3. Router

           accounts/views.py + mysite/urls.py (LEC 5 steps 14–15)


  from rest_framework import viewsets
  from django.contrib.auth.models import User
  from .serializers import UserSerializer


  class UserViewSet(viewsets.ModelViewSet):          # list, create, retrieve, update, destroy
        queryset = User.objects.all()                # inheritance (2.3) does the heavy lifting
        serializer_class = UserSerializer

--- PDF page 145 ---
# mysite/urls.py
  from rest_framework.routers import DefaultRouter
  from accounts.views import UserViewSet


  router = DefaultRouter()
  router.register("users", UserViewSet)                      # creates /api/users/ and /api/users/<id>/
  urlpatterns += [path("api/", include(router.urls))]



For custom logic that is not CRUD on one model (like an ML prediction), a view inherits from APIView and de‐
fines one method per HTTP verb ( def post(self, request) ).


▸ Token authentication and permissions

              settings.py + terminal (LEC 5 step 16)


  INSTALLED_APPS += ["rest_framework", "rest_framework.authtoken"]


  REST_FRAMEWORK = {
         "DEFAULT_AUTHENTICATION_CLASSES": [
               "rest_framework.authentication.TokenAuthentication",                    # reads "Authorization: Token
  ..."
               "rest_framework.authentication.SessionAuthentication",                  # keeps browser logins working
         ],
  }
  # $ python manage.py migrate                                          (creates the token table)
  # $ python manage.py drf_create_token <username>
  # $ curl -H "Authorization: Token <token>" http://127.0.0.1:8000/api/users/                            -> 200 JSON list



 Permission class                    Allows

  AllowAny                           everyone. This is DRF's default!

  IsAuthenticated                    only requests with a valid session or token (else 401 "Authentication credentials were not
                                     provided.")

  IsAdminUser                        only users with is_staff=True

  IsAuthenticatedOrReadOnl           anyone may read (GET); only logged-in users may change data
 y



  ⚠️ COMMON MISTAKE
  Adding rest_framework.authtoken only creates the token table. DEFAULT_AUTHENTICATION_CLASSES is
  what makes DRF read the header. And authentication never blocks anyone: without
     permission_classes = [IsAuthenticated] a view stays open to the whole internet (AllowAny).



   ✏️ FILL IN THE BLANKS: DRF
                books API

--- PDF page 146 ---
from rest_framework import serializers, ______                                                      # (1)
       from rest_framework.routers import ______                                                           # (2)


       class BookSerializer(serializers.______):                                                           # (3)
            class Meta:
                  model = Book
                  ______ = ["id", "title", "price"]                                                        # (4)


       class BookViewSet(viewsets.______):                                                                 # (5)
            queryset = Book.objects.______()                                                               # (6)
            ______ = BookSerializer                                                                        # (7)
            permission_classes = [______]                                                                  # (8) token required


       router = DefaultRouter()
       router.______("books", BookViewSet)                                                                 # (9)
       urlpatterns = [path("api/", include(router.______))]                                                # (10)



   🔓 Answer key: (1) viewsets · (2) DefaultRouter · (3) ModelSerializer · (4) fields · (5) ModelViewSet · (6) all · (7) serializer_class · (8)
   IsAuthenticated · (9) register · (10) urls




   PYQ        Final 2024-25 · Q6(a)                                                                                                         10 M


  Write Django code for Create and Read operations on an Employee model (id, name, salary) using
  Django REST Framework (DRF): 1. models.py: create the Employee model 2. serializers.py: serializer
  3. views.py: API views for CRUD 4. urls.py: URL patterns 5. API endpoints: URLs accessible via
  Postman/Thunder Client for Create and Read.

    Imports given:
    models.py                       from django.db import models
    serializers.py                  from rest_framework import serializers
                                    from .models import Employee
    views.py                        from rest_framework import viewsets
                                    from .models import Employee
                                    from .serializers import EmployeeSerializer
    urls.py (myapp)                 from django.urls import path
                                    from . import views
    urls.py (project)               from django.contrib import admin
                                    from django.urls import path, include



   ✓    MODEL ANSWER: WRITE THIS

  Setup: pip install django djangorestframework → django-admin startproject myproject →
    python manage.py startapp myapp , then register both apps:

               myproject/settings.py


       INSTALLED_APPS = [
            # ... default django apps ...

--- PDF page 147 ---
"rest_framework",
           "myapp",
     ]



  1. MODELS.PY

              myapp/models.py


     from django.db import models


     class Employee(models.Model):
           # id: auto-increment primary key added by Django automatically
           name = models.CharField(max_length=100)
           salary = models.DecimalField(max_digits=10, decimal_places=2)


           def __str__(self):
                return f"{self.id} - {self.name}"



    python manage.py makemigrations myapp and python manage.py migrate create the table
    myapp_employee(id, name, salary) .


  2. SERIALIZERS.PY

              myapp/serializers.py


     from rest_framework import serializers
     from .models import Employee


     class EmployeeSerializer(serializers.ModelSerializer):
           class Meta:
                model = Employee
                fields = ["id", "name", "salary"]                  # id is read-only automatically


           def validate_salary(self, value):                       # extra validation (optional)
                if value < 0:
                        raise serializers.ValidationError("Salary cannot be negative.")
                return value



  3. VIEWS.PY

              myapp/views.py


     from rest_framework import viewsets
     from .models import Employee
     from .serializers import EmployeeSerializer


     class EmployeeViewSet(viewsets.ModelViewSet):

--- PDF page 148 ---
"""list + create (Read/Create), and retrieve, update, partial_update, destroy"""
           queryset = Employee.objects.all()
           serializer_class = EmployeeSerializer
           # to allow ONLY Create and Read:    http_method_names = ["get", "post"]



  4. URLS.PY (APP AND PROJECT)

              myapp/urls.py: uses exactly the given imports (path + views)


     from django.urls import path
     from . import views


     employee_list = views.EmployeeViewSet.as_view({"get": "list", "post": "create"})
     employee_detail = views.EmployeeViewSet.as_view({"get": "retrieve", "put": "update",
                                                            "patch": "partial_update",
                                                            "delete": "destroy"})


     urlpatterns = [
           path("employees/", employee_list, name="employee-list"),                 # GET list, POST cre‐
     ate
           path("employees/<int:pk>/", employee_detail, name="employee-detail"),       # GET one
     ]



              myproject/urls.py


     from django.contrib import admin
     from django.urls import path, include


     urlpatterns = [
           path("admin/", admin.site.urls),
           path("api/", include("myapp.urls")),
     ]



  Equivalent with a router (the course's way): in myapp/urls.py write router = DefaultRouter() ,
    router.register("employees", views.EmployeeViewSet) ,
    urlpatterns = [path("", include(router.urls))] (imports:
    from rest_framework.routers import DefaultRouter , from django.urls import path, include ). It
  generates the same two URLs.

  5. API ENDPOINTS (POSTMAN / THUNDER CLIENT)
  Run python manage.py runserver . In Thunder Client/Postman: choose the method, enter the URL, for
  POST select Body → JSON, then Send.

--- PDF page 149 ---
Operation       Method + URL                          Body                            Response

    Create              POST                               {"name": "Asha",               201 Created {"id": 1, "name":
                    http://127.0.0.1:8000/ap              "salary": 55000}                "Asha", "salary": "55000.00"}
                    i/employees/

    Read all            GET                               none                            200 OK [{"id": 1, "name":
                    http://127.0.0.1:8000/ap                                              "Asha", ...}, ...]
                    i/employees/

    Read one            GET                               none                            200 OK {"id": 1, ...} or 404
                    http://127.0.0.1:8000/ap
                    i/employees/1/

    Invalid             POST                               {"name": ""}                   400 {"name": [...], "salary":
    create          .../api/employees/                                                    [...]}


               same tests with curl


     curl -X POST http://127.0.0.1:8000/api/employees/ \
              -H "Content-Type: application/json" \
              -d '{"name": "Asha", "salary": 55000}'
     curl http://127.0.0.1:8000/api/employees/
     curl http://127.0.0.1:8000/api/employees/1/



  (DRF returns DecimalField values as strings, "55000.00" , to keep them exact. Update and Delete use
  PUT/PATCH/DELETE on /api/employees/1/ .)

  🎯 Marking scheme guess: 1 M setup/INSTALLED_APPS · 2 M model · 2 M serializer · 2 M ViewSet · 2 M app + project urls · 1 M end‐
  points with method, body and response




    2.17 Machine-learning model integration
📚 Sources: Unit 2 Notes §8.1–8.4       LEC 5 (Django code-along) steps 17–25    Lecture 5 Commands Reference steps 17–25

 One-Shot Revision · custom prediction endpoint


A trained model is useful only when users and programs can send it inputs and get predictions back. The pat‐
tern has four rules, all from the course: train once, offline (training takes minutes, a request must answer in mil‐
liseconds); save it with joblib (a binary .pkl file, wb / rb modes); load once at module import, not per re‐
quest; validate input (Django form or DRF serializer) before calling model.predict() .

        train_model.py                  iris_model.pkl             views / ml_model.py                             input
    run once, outside Django
                                →         joblib.dump
                                                            →          joblib.load once
                                                                                              ←        IrisForm or IrisInputSerializer
                                                                                                                                         →

                                   model.predict([[4 numbers]])         →      HTML page or JSON

--- PDF page 150 ---
Line                                         Why it is there (Unit 2 Notes §8.3)

  model = joblib.load(...) at module          Python runs top-level code only on first import, so the file is read once when the
 top                                          server starts

  [[...]] , a list inside a list              scikit-learn always expects a batch of rows (2-D), even for one prediction

  int(p)                                      the result is a NumPy integer, which json cannot serialise

  is_valid(raise_exception=True)              bad input is stopped with a 400 before it reaches the model

  permission_classes =                        otherwise the AllowAny default lets anyone use the model
 [IsAuthenticated]


Iris: 4 features (sepal length, sepal width, petal length, petal width, in cm) → 3 classes: 0 setosa, 1 versicolor, 2
virginica. Input 5.1, 3.5, 1.4, 0.2 → 0 (setosa).


▸ The course's version: a protected DRF prediction endpoint

           mlpredict_iris/ml_model.py, serializers.py, views.py (LEC 5 steps 20–22)


  # ml_model.py: load once
  import joblib
  from pathlib import Path
  MODEL_PATH = Path(__file__).resolve().parent / "ml" / "iris_model.pkl"
  model = joblib.load(MODEL_PATH)


  # serializers.py: plain Serializer, no DB model behind the input
  from rest_framework import serializers
  class IrisInputSerializer(serializers.Serializer):
        sepal_length = serializers.FloatField()
        sepal_width = serializers.FloatField()
        petal_length = serializers.FloatField()
        petal_width = serializers.FloatField()


  # views.py: APIView, because prediction is one custom action, not CRUD
  from rest_framework.views import APIView
  from rest_framework.response import Response
  from rest_framework.permissions import IsAuthenticated
  from .serializers import IrisInputSerializer
  from .ml_model import model


  class PredictView(APIView):
        permission_classes = [IsAuthenticated]
        def post(self, request):
             serializer = IrisInputSerializer(data=request.data)
             serializer.is_valid(raise_exception=True)
             d = serializer.validated_data
             features = [[d["sepal_length"], d["sepal_width"], d["petal_length"], d["petal_width"]]]
             prediction = model.predict(features)[0]

--- PDF page 151 ---
return Response({"prediction": int(prediction)})


  # mysite/urls.py:           urlpatterns += [path("api/predict/", PredictView.as_view(), name="predict")]



            test it (LEC 5 step 23)


  curl -X POST http://127.0.0.1:8000/api/predict/ \
         -H "Content-Type: application/json" -H "Authorization: Token <token>" \
         -d '{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}'
  # {"prediction": 0}
  # without the token: {"detail": "Authentication credentials were not provided."}



Steps 24–25 add a logged-in browser page ( @login_required + @ensure_csrf_cookie ) whose JavaScript
 fetch es /api/predict/ with the session cookie and an X-CSRFToken header, so no token is pasted by
hand. Remember: run startapp mlpredict_iris before creating the mlpredict_iris/ml/ folder, and restart
 runserver after changing INSTALLED_APPS .


   ✏️ FILL IN THE BLANKS: ML INTEGRATION
    1. Save a trained model: joblib.                             (clf, "iris_model.pkl") ; load it:
         joblib.                   ("iris_model.pkl")

    2. Predict one flower: model.predict(                               5.1, 3.5, 1.4, 0.2                    )[0]

    3. Serializer for input with no DB table: serializers.                                  ; view for one custom action:


    4. Convert the NumPy result for JSON:                                 (prediction)

    5. Install the ML pieces: pip install                                 joblib


   🔓 Answer key: 1) dump · load 2) [[ · ]] 3) Serializer · APIView 4) int 5) scikit-learn

   PYQ        Final 2024-25 · Q7(a)                                                                                                10 M


  Integrate a Machine Learning model with a Django project to make predictions: an Iris dataset clas‐
  sification model, a Django form for user input, and display the predicted class. Write the steps and
  code for training, saving, and integrating the model for real-time prediction.

    Imports given:
    train_model.py               import pandas as pd
                                 from sklearn.datasets import load_iris
                                 from sklearn.model_selection import train_test_split
                                 from sklearn.ensemble import RandomForestClassifier
                                 import joblib
    forms.py                     from django import forms
    views.py                     from django.shortcuts import render
                                 import joblib
                                 from .forms import IrisForm
    urls.py (ml_app)             from django.urls import path
                                 from .views import predict

--- PDF page 152 ---
urls.py (project)       from django.contrib import admin
                            from django.urls import path, include



   ✓    MODEL ANSWER: WRITE THIS


  STEP 1: SETUP

              terminal


       pip install django scikit-learn pandas joblib
       django-admin startproject iris_project
       cd iris_project
       python manage.py startapp ml_app
       # settings.py -> INSTALLED_APPS = [..., "ml_app"]



  STEP 2: TRAIN AND SAVE THE MODEL (TRAIN_MODEL.PY, OUTSIDE DJANGO)

              train_model.py


       import pandas as pd
       from sklearn.datasets import load_iris
       from sklearn.model_selection import train_test_split
       from sklearn.ensemble import RandomForestClassifier
       import joblib


       # 1. load the dataset into a DataFrame
       iris = load_iris()
       df = pd.DataFrame(iris.data, columns=iris.feature_names)
       df["species"] = iris.target                   # 0 setosa, 1 versicolor, 2 virginica
       print(df.head())


       # 2. features X and label y (.values = plain arrays, so predict() can take a plain list)
       X = df.drop(columns="species").values
       y = df["species"].values


       # 3. split 80 % train / 20 % test
       X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)


       # 4. train a Random Forest classifier
       model = RandomForestClassifier(n_estimators=100, random_state=42)
       model.fit(X_train, y_train)
       print("Test accuracy:", model.score(X_test, y_test))


       # 5. save the trained model to disk
       joblib.dump(model, "iris_model.pkl")
       print("Model saved as iris_model.pkl")

--- PDF page 153 ---
Run once from the project folder: python train_model.py . It creates iris_model.pkl next to
    manage.py .


  STEP 3: THE DJANGO FORM

              ml_app/forms.py


     from django import forms


     class IrisForm(forms.Form):
           sepal_length = forms.FloatField(label="Sepal length (cm)", min_value=0)
           sepal_width = forms.FloatField(label="Sepal width (cm)", min_value=0)
           petal_length = forms.FloatField(label="Petal length (cm)", min_value=0)
           petal_width = forms.FloatField(label="Petal width (cm)", min_value=0)



  STEP 4: THE PREDICTION VIEW

              ml_app/views.py


     from django.shortcuts import render
     import joblib
     from .forms import IrisForm


     model = joblib.load("iris_model.pkl")              # loaded ONCE when Django imports this module
     SPECIES = ["Setosa", "Versicolor", "Virginica"]


     def predict(request):
           prediction = None
           if request.method == "POST":
                form = IrisForm(request.POST)           # bind user input
                if form.is_valid():                     # validate: numbers, not negative
                        d = form.cleaned_data
                        features = [[d["sepal_length"], d["sepal_width"],
                                    d["petal_length"], d["petal_width"]]]      # 2-D: one row
                        class_id = model.predict(features)[0]
                        prediction = SPECIES[int(class_id)]
           else:
                form = IrisForm()                       # GET: empty form
           return render(request, "predict.html", {"form": form, "prediction": prediction})



  The relative path "iris_model.pkl" is resolved from the folder where python manage.py runserver is
  started (the one with manage.py ). The course's more robust alternative is
    Path(__file__).resolve().parent / "ml" / "iris_model.pkl" .


  STEP 5: URLS

              ml_app/urls.py

--- PDF page 154 ---
from django.urls import path
     from .views import predict


     urlpatterns = [
           path("", predict, name="predict"),
     ]


     # iris_project/urls.py
     from django.contrib import admin
     from django.urls import path, include


     urlpatterns = [
           path("admin/", admin.site.urls),
           path("", include("ml_app.urls")),
     ]



  STEP 6: TEMPLATE TO SHOW THE FORM AND THE PREDICTED CLASS

              ml_app/templates/predict.html


     <!DOCTYPE html>
     <html>
     <head><title>Iris Predictor</title></head>
     <body>
         <h2>Iris Flower Classification</h2>
         <form method="post">
           {% csrf_token %}
           {{ form.as_p }}
           <button type="submit">Predict</button>
         </form>


         {% if prediction %}
           <h3>Predicted class: {{ prediction }}</h3>
         {% endif %}
     </body>
     </html>



  STEP 7: RUN AND TEST

    python manage.py runserver → open http://127.0.0.1:8000/ → enter 5.1, 3.5, 1.4, 0.2 → Predicted
  class: Setosa. Invalid input (text, negative numbers) re-displays the form with error messages; the model is
  never called. No redirect is needed after this POST because nothing is saved to the database.

  Variant (course, LEC 5): expose the same model as a JSON API with an IrisInputSerializer +
    APIView ( PredictView , permission_classes = [IsAuthenticated] ) at POST /api/predict/ return‐
  ing {"prediction": 0} , as shown just above this question.

--- PDF page 155 ---
🎯 Marking scheme guess: 2 M training script + joblib.dump · 2 M IrisForm · 3 M view (load once, is_valid, cleaned_data, predict, render) ·
  1 M urls · 1 M template · 1 M steps/flow




    2.18 Case study: the Enrollments system
📚 Sources: Unit 2 Notes §4.6–4.7, §5.2–5.3, §6.4       LEC 4 (Python · Django) slides 15–19       One-Shot Revision · Django MVT

 Complete Revision deck U2 slides 15–18       Gap topics G13 + G16 (2.9, 2.13)


  ✍️ HOW TO ATTACK Q7 (20 MARKS)
  This is the newest paper's scenario question, and it rewards design reasoning as well as code. For each
  part: (1) one line saying what you are designing, (2) the code, (3) a short bullet list explaining the decisions
  (types, constraints, HTTP method, validation, why the redirect). The same answer shape works for any "Li‐
  brary / Hospital / Hostel" variant: two main models plus one join model with two ForeignKeys.



                      Student                                Enrollment (join)                                          Course

       id PK (auto)                                   id PK (auto)                                       id PK (auto)
       roll_no Char, UNIQUE                  1    N   student FK → Student                    N      1   code Char, UNIQUE
       name Char(100)                                 course FK → Course                                 title Char(200)
       email Email, UNIQUE                            enrolled_on DateTime (auto)                        credits PositiveSmallInt
       year PositiveSmallInt                          status ACTIVE | DROPPED | …                        capacity PositiveInt
       courses M2M through=                           UNIQUE (student, course)
       "Enrollment"                                   on_delete = CASCADE


                      Student 1 : N Enrollment N : 1 Course = Student M : N Course (many-to-many through Enrollment)


Data model: two one-to-many relationships through the join table form a many-to-many relationship that also stores data about each enrollment.



   PYQ         Final 2025-26 · Q7(A)   ★ LATEST                                                                                        6M


  Scenario: Enrollments feature for a university website using Django MVT; link Students to Courses
  through an Enrollment model. Define Django models Student, Course, Enrollment: fields with data
  types; primary keys and foreign keys; uniqueness constraints / validation; relationship type (one-to-
  many, many-to-many); methods (__str__, custom).

   ✓     MODEL ANSWER: WRITE THIS

                enrollments/models.py


       from django.core.exceptions import ValidationError
       from django.db import models




       class Student(models.Model):
            roll_no = models.CharField(max_length=20, unique=True)
            name = models.CharField(max_length=100)

--- PDF page 156 ---
email = models.EmailField(unique=True)
           year = models.PositiveSmallIntegerField(default=1)
           courses = models.ManyToManyField("Course", through="Enrollment", related_name="students")


           def __str__(self):
                return f"{self.roll_no} - {self.name}"


           def active_enrollments(self):                              # custom method
                return self.enrollments.filter(status=Enrollment.Status.ACTIVE)


           def total_credits(self):                                   # custom method
                return sum(e.course.credits for e in self.active_enrollments())




     class Course(models.Model):
           code = models.CharField(max_length=10, unique=True)        # e.g. "CS101"
           title = models.CharField(max_length=200)
           credits = models.PositiveSmallIntegerField(default=3)
           capacity = models.PositiveIntegerField(default=60)


           def __str__(self):
                return f"{self.code}: {self.title}"


           def seats_left(self):                                      # custom method
                taken = self.enrollments.filter(status=Enrollment.Status.ACTIVE).count()
                return self.capacity - taken


           def is_full(self):
                return self.seats_left() <= 0




     class Enrollment(models.Model):                                 # the join ("through") model
           class Status(models.TextChoices):
                ACTIVE = "ACTIVE", "Active"
                DROPPED = "DROPPED", "Dropped"
                COMPLETED = "COMPLETED", "Completed"


           student = models.ForeignKey(Student, on_delete=models.CASCADE,
     related_name="enrollments")
           course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="enrollments")
           enrolled_on = models.DateTimeField(auto_now_add=True)
           status = models.CharField(max_length=10, choices=Status.choices, default=Status.ACTIVE)


           class Meta:
                constraints = [
                        models.UniqueConstraint(fields=["student", "course"],

--- PDF page 157 ---
name="unique_student_course"),
                  ]
                  ordering = ["-enrolled_on"]


              def __str__(self):
                  return f"{self.student.name} -> {self.course.code} ({self.status})"


              def clean(self):                                                      # validation: no seat, no enroll‐
       ment
                  if self.pk is None and self.course_id and self.course.is_full():
                        raise ValidationError("This course is full.")



        Fields and types: text as CharField (with max_length ), EmailField (format validated), small
        counts as PositiveSmallIntegerField (no negatives), timestamp as
         DateTimeField(auto_now_add=True) (set once, automatically), status as a CharField with
         choices .

        Primary keys: each model gets an auto-increment id PK from Django. Foreign keys:
         Enrollment.student → Student and Enrollment.course → Course (columns student_id ,
         course_id ), on_delete=CASCADE so deleting a student or course removes its enrollments (use
         PROTECT to forbid deleting a course that has students).

        Uniqueness / validation: roll_no , email and code are unique=True ;
         UniqueConstraint(student, course) makes it impossible (at database level) to enroll the same stu‐
        dent twice in one course; clean() blocks enrolling in a full course; choices restricts status .
        Relationship: Student–Enrollment is one-to-many, Course–Enrollment is one-to-many; together they
        make Student–Course many-to-many. A plain ManyToManyField would hide the join table, but we
        need extra data (date, status), so Enrollment is an explicit through model, exposed as
         student.courses.all() / course.students.all() .

        Methods: __str__ gives readable labels in admin and shell; custom methods seats_left() ,
         is_full() , active_enrollments() , total_credits() keep business logic in the model, not in
        templates.

  🎯 Marking scheme guess: 2 M three models with correct field types · 1 M PK/FK + on_delete · 1 M unique constraints + validation · 1 M
  relationship explanation · 1 M __str__ + custom methods




   PYQ         Final 2025-26 · Q7(B)   ★ LATEST                                                                                   6M


  Three URL–View mappings: 1. list all courses a student is enrolled in; 2. enroll a student into a new
  course (form submission); 3. unenroll / drop. For each: URL pattern (e.g. /student/<id>/courses/),
  HTTP method (GET/POST/DELETE), and what the view does (query logic, validation, response).

   ✓    MODEL ANSWER: WRITE THIS

--- PDF page 158 ---
#          URL pattern             Method             View does                                          Response

    1 List      student/<int:stu‐      GET                 get_object_or_404(Student) ;                      200 rendered list (404 if
               dent_id>/courses/                          query ACTIVE enrollments with selec‐               no student)
                                                          t_related("course")

    2           student/<int:stu‐      GET shows form;    bind EnrollForm , is_valid()                       302 redirect to list
    Enroll     dent_id>/enroll/        POST submits       (course exists, not already enrolled, not full);   (PRG); invalid → 200
                                                          create inside                                      form with errors
                                                           transaction.atomic()

    3           student/<int:stu‐      POST (HTML         find the ACTIVE enrollment (404 otherwise),        302 redirect to list
    Drop       dent_id>/courses/<      forms can't send   set status = DROPPED
               int:course_id>/dro      DELETE)
               p/


               enrollments/urls.py (included from the project urls.py)


     from django.urls import path
     from . import views


     urlpatterns = [
             path("student/<int:student_id>/courses/", views.student_courses, name="student-courses"),
             path("student/<int:student_id>/enroll/", views.enroll, name="enroll"),
             path("student/<int:student_id>/courses/<int:course_id>/drop/", views.drop, name="drop"),
     ]



               enrollments/forms.py


     from django import forms
     from .models import Course, Enrollment


     class EnrollForm(forms.Form):
             course = forms.ModelChoiceField(queryset=Course.objects.all(), empty_label="Choose a
     course")


             def __init__(self, *args, student=None, **kwargs):
                super().__init__(*args, **kwargs)
                self.student = student


             def clean_course(self):
                course = self.cleaned_data["course"]
                if Enrollment.objects.filter(student=self.student, course=course,
                                                   status=Enrollment.Status.ACTIVE).exists():
                        raise forms.ValidationError("Already enrolled in this course.")
                if course.is_full():
                        raise forms.ValidationError("This course is full.")
                return course

--- PDF page 159 ---
enrollments/views.py


     from django.contrib import messages
     from django.contrib.auth.decorators import login_required
     from django.db import transaction
     from django.shortcuts import get_object_or_404, redirect, render
     from django.views.decorators.http import require_GET, require_POST, require_http_methods
     from .forms import EnrollForm
     from .models import Enrollment, Student




     @login_required
     @require_GET
     def student_courses(request, student_id):                                   # 1. LIST
           student = get_object_or_404(Student, pk=student_id)
           enrollments = (student.enrollments
                              .filter(status=Enrollment.Status.ACTIVE)
                              .select_related("course")                      # one JOIN, not N queries
                              .order_by("course__code"))
           return render(request, "enrollments/student_courses.html",
                              {"student": student, "enrollments": enrollments,
                              "total_credits": student.total_credits()})




     @login_required
     @require_http_methods(["GET", "POST"])
     def enroll(request, student_id):                                            # 2. ENROLL
           student = get_object_or_404(Student, pk=student_id)
           if request.method == "POST":
                form = EnrollForm(request.POST, student=student)
                if form.is_valid():
                        course = form.cleaned_data["course"]
                        with transaction.atomic():                           # all-or-nothing
                           Enrollment.objects.update_or_create(              # new row, or re-activate
                                student=student, course=course,              # a previously dropped one
                                defaults={"status": Enrollment.Status.ACTIVE})
                        messages.success(request, f"Enrolled in {course.code}.")
                        return redirect("student-courses", student_id=student.id)      # PRG
           else:
                form = EnrollForm(student=student)
           return render(request, "enrollments/enroll.html", {"student": student, "form": form})




     @login_required
     @require_POST
     def drop(request, student_id, course_id):                               # 3. DROP

--- PDF page 160 ---
enrollment = get_object_or_404(Enrollment, student_id=student_id, course_id=course_id,
                                                   status=Enrollment.Status.ACTIVE)
           enrollment.status = Enrollment.Status.DROPPED                                    # soft delete keeps history
           enrollment.save(update_fields=["status"])
           messages.info(request, f"Dropped {enrollment.course.code}.")
           return redirect("student-courses", student_id=student_id)



        Why POST for drop: it changes data, so it must never be a GET link (a crawler or prefetch could trigger
        it), and HTML forms support only GET/POST. In a REST API (DRF) the same action is
         DELETE /api/students/7/enrollments/3/ → 204 No Content, and enroll is
         POST /api/students/7/enrollments/ → 201 Created.

        Security: @login_required on every view; in production also check that request.user owns this
        student record or is staff (else 403). require_POST returns 405 for a GET. CSRF tokens protect both
        POST forms.
        Integrity: the form gives friendly errors; the DB UniqueConstraint is the final guard against double
        clicks and race conditions; transaction.atomic() rolls back on any error (add
         select_for_update() on the course to lock the last seat).


  🎯 Marking scheme guess: 2 M per mapping: URL + method (1) and view logic with validation and response (1)

   PYQ       Final 2025-26 · Q7(C)   ★ LATEST                                                                                 4M


  What should the template display on the course listing page: what information is rendered (student
  details, course list, enrollment dates); what user actions (enroll / unenroll buttons); what logic should
  NOT be in the template (business logic, complex queries); how data is passed from view to template.

   ✓    MODEL ANSWER: WRITE THIS

                enrollments/templates/enrollments/student_courses.html


       {% extends "base.html" %}
       {% block content %}
       <h2>{{ student.name }} ({{ student.roll_no }})</h2>
       <p>{{ student.email }} · Year {{ student.year }} · {{ total_credits }} credits</p>


       {% for m in messages %}<p class="msg">{{ m }}</p>{% endfor %}


       <table>
         <tr><th>Code</th><th>Course</th><th>Credits</th><th>Enrolled on</th><th>Status</th><th>
       </th></tr>
         {% for e in enrollments %}
         <tr>
           <td>{{ e.course.code }}</td>
           <td>{{ e.course.title }}</td>
           <td>{{ e.course.credits }}</td>
           <td>{{ e.enrolled_on|date:"d M Y" }}</td>

--- PDF page 161 ---
<td>{{ e.get_status_display }}</td>
           <td>
              <form method="post" action="{% url 'drop' student.id e.course.id %}">
                 {% csrf_token %}
                 <button type="submit">Drop</button>
              </form>
           </td>
        </tr>
        {% empty %}
        <tr><td colspan="6">Not enrolled in any course yet.</td></tr>
        {% endfor %}
     </table>
     <a href="{% url 'enroll' student.id %}">+ Enroll in a new course</a>
     {% endblock %}



       Information rendered: student details (name, roll no, email, year, total credits), and for each active en‐
       rollment the course code, title, credits, enrollment date (formatted with |date ) and status; an empty-
       state message via {% empty %} ; success/error flash messages.
       User actions: a Drop button per row (a small POST form with {% csrf_token %} , since it changes
       data) and an Enroll in a new course link to the enroll form; URLs built with {% url %} , never hard-
       coded.
       Must NOT be in the template: business rules (capacity check, duplicate check, who may drop), data‐
       base queries or filtering (e.g. picking only ACTIVE rows), calculations like total credits, and permission
       decisions. These live in the view/model/form. The template only displays data, and DTL deliberately
       cannot run arbitrary Python.
       Passing data: the view calls render() with a context dict,
        {"student": student, "enrollments": enrollments, "total_credits": ...} ; each key of the
       context dictionary becomes a template variable, accessed with {{ }} and dot lookup
       ( e.course.title ). request.user and messages are added automatically by context processors.

  🎯 Marking scheme guess: 1 M information shown · 1 M actions (buttons/forms with CSRF) · 1 M what stays out of templates · 1 M con‐
  text dict via render()

--- PDF page 162 ---
Browser                           Middleware + urls.py                     enroll view + form                       Database

                        1 POST /student/7/enroll/
                    course=3 · csrf token · sessionid

                                                           2 session → user, CSRF ✓
                                                                 3 URL match → enroll()


                                                                                                4 login? student 404?


                                                                                                5 form.is_valid()
                                                                                                duplicate? course full?
                                                                                                       6 atomic: INSERT row


                                                                                                       COMMIT (or ROLLBACK)
                               7 302 Redirect (PRG) · 8 invalid: 200 form + errors


                                9 GET /student/7/courses/ → list view queries DB

                               200 OK: rendered course list + "Enrolled in CS101"




                                    The enroll POST as a sequence diagram (numbers match the answer below).



   PYQ       Final 2025-26 · Q7(D)   ★ LATEST                                                                                             4M


  Give a numbered sequence of the complete request–response flow when a user submits the form to
  enroll (POST): 1 browser form submission, 2 Django receives the request, 3 URL routing and view ex‐
  ecution, 4 form validation, 5 database operations, 6 response generation, 7 redirect or error handling
  (aim for 7–9 steps).

   ✓    MODEL ANSWER: WRITE THIS


    1        Browser form submission. The user picks a course on /student/7/enroll/ and clicks Enroll.
             The browser sends POST /student/7/enroll/ with body course=3&csrfmiddlewaretoken=…
             and its cookies ( sessionid , csrftoken ).

    2        Django receives the request. The server (runserver / gunicorn via WSGI) builds an HttpRequest .
             Middleware runs: SessionMiddleware loads the session, AuthenticationMiddleware sets
              request.user , CsrfViewMiddleware compares the tokens (mismatch → 403 Forbidden).


    3        URL routing. The root urls.py                   include() s the app URLs; the pattern
              student/<int:student_id>/enroll/ matches and Django calls
              enroll(request, student_id=7) .


    4        View execution. Decorators run first: @login_required (anonymous → 302 to login),
              @require_http_methods (wrong method → 405). The view loads the student with
              get_object_or_404 (→ 404) and binds EnrollForm(request.POST, student=student) .


    5        Form validation. form.is_valid() converts "3" to a Course object (it must exist) and runs
              clean_course() : not already enrolled, course not full. Results go to cleaned_data or
              form.errors .

--- PDF page 163 ---
6         Database operations. Inside transaction.atomic() the ORM runs update_or_create , i.e. an
                INSERT INTO enrollments_enrollment (student_id, course_id, enrolled_on, status) ; the
               UNIQUE(student, course) constraint guarantees no duplicate; the transaction COMMITs (or ROLLs
               BACK on error).

     7         Response generation (success). A flash message is stored ( messages.success ) and the view re‐
               turns redirect("student-courses", student_id=7) , a 302 with
                Location: /student/7/courses/ (Post/Redirect/Get, so a refresh cannot re-submit).


     8         Error handling. If validation fails, nothing is written; the view re-renders enroll.html with the
               bound form → 200 showing "This course is full." / "Already enrolled", with the user's choice kept.
               An IntegrityError from a race is rolled back and reported the same way.

     9         Redirect followed. The browser automatically sends GET /student/7/courses/ ; the list view
               queries the active enrollments, renders the template, and returns 200 OK HTML showing the new
               course and the success message.


  🎯 Marking scheme guess: ~0.5 M per correct step in the right order (7 required, 9 for full marks), with CSRF, is_valid, atomic save and
  PRG redirect named explicitly




  🧠 RELATED QUESTIONS IN OTHER CHAPTERS
  Final 2025-26 Q4(C), "How a Django backend interacts with SPA vs RSC", is answered in the Unit 4
  chapter (Django sends JSON via DRF/JsonResponse to an SPA; more API endpoints are needed for the
  SPA). Final 2025-26 Q5(B), "ORM with SQL vs NoSQL", is answered in the Unit 3 chapter. Both build on
  2.9–2.11 and 2.16 here.




     2.19 Likely questions for 2026
📚 Sources: Pattern analysis of Final 2025-26, Final 2024-25, Re-Exam 2023-24
The newest paper moved from "write the code" to explain + design + trace. Expect one 20-mark Python/OOP
question and one 20-mark Django scenario again, plus a short Django part in Q1.

 #       Likely question                                                 Marks     Answer pointer

 1       A new scenario (Library: Book/Member/Loan, Hospital:            20        2.18: copy the shape: two models + through model with
         Doctor/Patient/Appointment): models, URL–view mappings,                   two FKs, UniqueConstraint, PRG flow
         template, POST flow

 2       Code reading: shallow vs deep copy, is vs == , tuple            6         2.2: draw names → objects; deepcopy for nested data
         holding a list, mutable default argument

 3       Instance vs class vs static methods with code; __str__          6–10      2.3: Student example + tables
         vs __repr__ ; four pillars of OOP

 4       Explain MVT with a diagram and trace one request (GET           10        2.6 diagram + 7 steps; 2.7 structure
         /orders/7/)

--- PDF page 164 ---
#     Likely question                                                      Marks     Answer pointer

 5     ORM queries for a model and the equivalent SQL (filter,              10        2.10 table + B-Q3b answer
       range, order_by, aggregate, values)

 6     DRF: serializer, ViewSet, router, token authentication, per‐         10        2.16 + B-Q6a; authtoken +
       missions; why AllowAny is dangerous                                            DEFAULT_AUTHENTICATION_CLASSES +
                                                                                      IsAuthenticated

 7     Sessions vs cookies; authentication vs authorization; how            6         2.14 flow + tables; 2.13 CSRF
        login() works; CSRF

 8     Serving an ML model: train once / load once / validate / pre‐        10        2.17 + B-Q7a
       dict, form vs API endpoint

 9     SQLite vs PostgreSQL; switching databases; raw SQL with              4–6       2.15
       placeholders vs SQL injection

 10    Python socket client/server code; HTTP methods and status            4–6       2.4 echo server/client + tables
       codes




      2.20 Last-minute recap
📚 Sources: Unit 2 Notes §9          LEC 4 (Python · Django) slide 24     LEC 5 (Django code-along) slides 29–30   One-Shot Revision

 Complete Revision deck U2

--- PDF page 165 ---
PYTHON                                                          DJANGO

       list [ ] mutable · tuple ( ) immutable · dict                   MVT: Model = data, View = logic (MVC con‐
       key→value · set unique; {} = dict, set() =                      troller), Template = HTML (MVC view); urls.py
       empty set.                                                      routes.
       Mutable: list, dict, set. Immutable: int, float, str,           Project = settings + root URLs; app = feature,
       tuple, frozenset, bool.                                         must be in INSTALLED_APPS .
         y = x → alias (same id); .copy() → new                         makemigrations writes the file; migrate ap‐
       outer object (shallow); copy.deepcopy() →                       plies it.
       copies everything.                                              ForeignKey = many-to-one (+ on_delete); M2M
       Dict keys must be hashable (immutable) →                        with extra data = through model.
         TypeError: unhashable type: 'list' .                          Unique: unique=True ,
         *args → tuple, **kwargs → dict. try / ex‐                      UniqueConstraint(fields=[...],
       cept / else / finally.                                          name=...) ; clean() runs only via full_clean /

         __init__ constructor (after __new__ ),                        ModelForm.
         self = this object, __del__ destructor (ref‐                  render (HTML page) · HttpResponse (raw text)
       count 0 / GC).                                                  · JsonResponse (JSON, safe=False for lists).
       Instance (self) · @classmethod (cls) · @stat‐                   Form view: bind → is_valid → cleaned_data →
       icmethod (neither).                                             save → redirect (PRG); invalid → re-render.
       Pillars: Abstraction, Polymorphism,                              {% csrf_token %} in every POST form; 403
       Inheritance, Encapsulation ("A PIE").                           without it.
       Socket server: socket → bind → listen → ac‐                     Session: only sessionid in the cookie; data in
       cept → recv/send → close. Bytes:                                the django_session table.
       encode/decode.                                                  DRF: Serializer   ⇄ JSON, ModelViewSet =
       Files: r / w (overwrite) / a / x / r+, +b; with                 CRUD, DefaultRouter writes URLs; Token
       open() auto-closes. json: dumps/loads                           header; default permission AllowAny.
       (string), dump/load (file).                                     ML: train once → joblib.dump → load once at
                                                                       import → validate → predict([[...]]) →
                                                                       int().


 Need                   Command / code skeleton

 New project +          django-admin startproject mysite . · python manage.py startapp accounts
 app

 DB tables              python manage.py makemigrations · python manage.py migrate

 Admin                  createsuperuser · admin.site.register(Model) · /admin/

 Shell / SQL            python manage.py shell · print(qs.query) · dbshell

 Postgres               pip install psycopg2-binary · ENGINE django.db.backends.postgresql , PORT 5432

 DRF                    pip install djangorestframework · "rest_framework" in INSTALLED_APPS

 Token                  "rest_framework.authtoken" + DEFAULT_AUTHENTICATION_CLASSES · drf_create_token
                        user

 Model                  class X(models.Model): f = models.CharField(max_length=100) + __str__

--- PDF page 166 ---
Need                   Command / code skeleton

 View                   def v(request): return render(request, "t.html", {"k": v})

 URL                    path("x/<int:pk>/", views.v, name="x") · include("app.urls")

 Serializer             class S(serializers.ModelSerializer): class Meta: model = X; fields =
                        "__all__"

 ViewSet                class V(viewsets.ModelViewSet): queryset = X.objects.all(); serializer_class =
                        S

 Router                 router = DefaultRouter(); router.register("xs", V) · path("api/",
                        include(router.urls))

 Auth                   authenticate() → login() · logout() · @login_required · create_user()