FSD Module 1
FSD Module 1
UNIVERSITY
JNANA SANGAMA, BELGAVI-590018, KARNATAKA
Fullstack Development
(As per CBCS Scheme 2021)
PREPARED BY:
DEEPA B (ASST.PROF DEPT OF CSE, KNSIT)
INDHUMATHI R (ASST.PROF DEPT OF DS (CSE), KNSIT)
Module-1:
MVC based Web Designing Web framework, MVC Design Pattern, Django Evolution, Views, Mapping URL to
Views, Working of Django URL Confs and Loose Coupling, Errors in Django, Wild Card patterns in URLS.
Module-2:
Django Templates and Models Template System Basics, Using Django Template System, Basic Template Tags
and Filters, MVT Development Pattern, Template Loading, Template Inheritance, MVT Development Pattern.
Configuring Databases, Defining and Implementing Models, Basic Data Access, Adding Model String
Representations, Inserting/Updating data, Selecting and deleting objects, Schema Evolution
Module-3:
Django Admin Interfaces and Model Forms Activating Admin Interfaces, Using Admin Interfaces, Customizing
Admin Interfaces, Reasons to use Admin Interfaces. Form Processing, Creating Feedback forms, Form
submissions, custom validation, creating Model Forms, URLConf Ticks, Including Other URLConfs.
Module-4:
Generic Views and Django State Persistence Using Generic Views, Generic Views of Objects, Extending
Generic Views of objects, Extending Generic Views. MIME Types, Generating Non-HTML contents like CSV
and PDF, Syndication Feed Framework, Sitemap framework, Cookies, Sessions, Users and Authentication.
Module-5:
jQuery and AJAX Integration in Django Ajax Solution, Java Script, XHTMLHttpRequest and Response, HTML,
CSS, JSON, iFrames, Settings of Java Script in Django, jQuery and Basic AJAX, jQuery AJAX Facilities, Using
jQuery UI Autocomplete in Django
Textbooks:
1. Adrian Holovaty, Jacob Kaplan Moss, The Definitive Guide to Django: Web Development Done Right,
Second Edition, Springer-Verlag Berlin and Heidelberg GmbH & Co. KG Publishers, 2009
2. Jonathan Hayward, Django Java Script Integration: AJAX and jQuery, First Edition, Pack Publishing, 2011
Reference Books:
1. Aidas Bendroraitis, Jake Kronika, Django 3 Web Development Cookbook, Fourth Edition, Packt Publishing,
2020
2. William Vincent, Django for Beginners: Build websites with Python and Django, First Edition, Amazon
Digital Services, 2018 3. Antonio Mele, Django
4. Arun Ravindran, Django Design Patterns and Best Practices, 2nd Edition, Pack Publishers, 2020.
5. Julia Elman, Mark Lavin, Light weight Django, David A. Bell, 1st Edition, Oreily Publications, 2014
2
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
Examples:
1. Django (Python): Django is a high-level web framework for Python that follows the MVC pattern.
It provides a robust set of features for building web applications, including an ORM, URL routing,
form handling, session management, and a built-in admin interface.
2. Flask (Python): Flask is a lightweight web framework for Python that is designed to be simple and
easy to use. It provides essential features for building web applications, such as URL routing, template
rendering, and support for extensions.
3. Ruby on Rails (Ruby): Ruby on Rails is a popular web framework for Ruby that follows the MVC
pattern. It emphasizes convention over configuration and includes features like ActiveRecord (ORM),
URL routing, form helpers, and built-in support for testing.
4. Express.js (JavaScript/Node.js): Express.js is a minimal and flexible web framework for Node.js
that is used for building web applications and APIs. It provides a simple yet powerful API for defining
routes, middleware, and handling HTTP requests and responses.
5. ASP.NET Core (C#): ASP.NET Core is a cross-platform web framework for building modern,
cloud based web applications using C#. It includes features like MVC pattern support, middleware
pipeline, dependency injection, and built-in support for authentication and authorization.
The Model View Controller (MVC) design pattern specifies that an application consists of a data
model, presentation information, and control information. The pattern requires that each of these be
separated into different objects.
● The MVC pattern separates the concerns of an application into three distinct components, each
responsible for a specific aspect of the application’s functionality
3
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
● This separation of concerns makes the application easier to maintain and extend, as changes to one
component do not require changes to the other components.
1. Model :
The Model component in the MVC (Model-View-Controller) design pattern represents the data and
business logic of an application. It is responsible for managing the application’s data, processing
business rules, and responding to requests for information from other components, such as the View
and the Controller.
2. View:
Displays the data from the Model to the user and sends user inputs to the Controller. It is passive and
does not directly interact with the Model. Instead, it receives data from the Model and sends user inputs
to the Controller for processing.
3. Controller: Controller acts as an intermediary between the Model and the View. It handles user
input and updates the Model accordingly and updates the View to reflect changes in the Model. It
contains application logic, such as input validation and data transformation
4
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
This below communication flow ensures that each component is responsible for a specific aspect of
the application’s functionality, leading to a more maintainable and scalable architecture.
■ The user interacts with the View, such as clicking a button or entering text into a form.
■ The View receives the user input and forwards it to the Controller.
■ It interprets the input, performs any necessary operations (such as updating the Model), and
decides how to respond.
■ The Controller updates the Model based on the user input or application logic.
■ The View requests data from the Model to update its display.
■ The Controller updates the View based on the changes in the Model or in response to user input.
■ The View renders the updated UI based on the changes made by the Controller.
5
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
Features of Django:
1. Rapid Development: Django was designed with the intention to make a framework which
takes less time to build web application. The project implementation phase is a very time taken
but Django creates it rapidly.
2. Secure: Django takes security seriously and helps developers to avoid many common security
mistakes, such as SQL injection, cross-site scripting, cross-site request forgery etc. Its user
authentication system provides a secure way to manage user accounts and passwords.
3. Scalable: Django is scalable in nature and has ability to quickly and flexibly switch from small
to large scale application project. Fully loaded Django includes various helping task modules
and libraries which can be used to handle common Web development tasks. Django takes care
of user authentication, content administration, site maps, RSS feeds etc
4. Versatile: Django is versatile in nature which allows it to build applications for different-
different domains. Now a days, Companies are using Django to build various types of
applications like: content management systems, social networks sites or scientific computing
platforms etc. Open Source Django is an open source web application framework. It is publicly
available without cost. It can be downloaded with source code from the public repository. Open
source reduces the total cost of the application development.
5. Vast and Supported Community: Django is an one of the most popular web framework. It
has widely supportive community and channels to share and connect. Django Simplifies many
of the common tasks
1. Database Access - it consist of ORM (Object Relational Manager - abstract layer - easy to
interact with database) that simplifies database access
2. Form Validation - easy way to validate data submitted via a forms, check for correct format
also
3. User Authentication - Inbuilt authentication system
4. Data Serialization - allow developers to easily convert data into formats like JSON to easily
transfer it to the web.
Web application - some software running on the web browser over the internet. Restful Web
API - system that will provide data on proper request from the client.
6
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
DJANGO EVOLUTION:
The evolution of Django, a popular web framework for building web applications in Python, has been
marked by significant milestones and improvements over the years. Here's a brief overview of its
evolution:
1. Initial Release (2005): Django was originally developed by Adrian Holovaty and Simon Willison
while working at the Lawrence Journal-World newspaper. It was first released as open-source
software in July 2005, with the goal of enabling developers to build web applications quickly and
efficiently.
2. Version 0.90 (2006): The first official release of Django (version 0.90) occurred in September 2006.
This version introduced many of the core features that Django is known for, including its ORM
(ObjectRelational Mapping) system, its templating engine, and its admin interface.
3. Stable Releases and Growth (2007-2010): Over the next few years, Django continued to grow in
popularity and maturity. The development team released several stable versions, adding new
features, improving performance, and enhancing documentation.
4. Django 1.0 (2008): A significant milestone in Django's evolution was the release of version 1.0 in
September 2008. This marked the stabilization of the framework's API and signaled Django's
readiness for production use in a wide range of applications.
5. Django 1.x Series (2008-2015): The 1.x series of Django brought further refinements and
enhancements to the framework. These included improvements to the ORM, support for more
database backends, enhancements to the admin interface, and better support for internationalization
and localization.
6. Django 1.11 LTS (2017): Django 1.11 was designated as a Long-Term Support (LTS) release, meaning
it would receive security updates and bug fixes for an extended period. LTS releases are particularly
important for organizations that require stability and long-term support for their Django applications.
7. Django 2.0 (2017): Django 2.0, released in December 2017, introduced several major changes,
including support for Python 3.4 and higher as well as dropping support for Python 2.x. It also
introduced asynchronous views and other improvements.
8. Django 3.x Series (2019-2022): The 3.x series of Django continued to build on the improvements
introduced in Django 2.0. It further refined support for asynchronous views, introduced new features
such as path converters, and continued to improve performance and security.
9. Django 4.0 (2022): Django 4.0, released in December 2022, brought significant changes and
improvements, including support for Python 3.10 and higher as well as dropping support for older
Python versions. It also introduced stricter settings, improved model inheritance, and other
enhancements.
7
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
URLs
In Django, URLs are defined in the urls.py file. This file contains a list of URL patterns that map to
views. A URL pattern is defined as a regular expression that matches a URL. When a user requests a
URL, Django goes through the list of URL patterns defined in the urls.py file and finds the first pattern
that matches the URL. If no pattern matches, Django returns a 404 error. The urls.py file provides a
way to map a URL to a view. A view is a Python callable that takes a request and returns an HTTP
response. To map a URL to a view, we can create a urlpatterns list in the urls.py file. Each element of
the list is a path() or re_path() function call that maps a URL pattern to a view.
Here is an example of a simple urls.py file:
from django.urls import path
from . import views
urlpatterns =
[ path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'), ]
In this example, we have three URL patterns. The first pattern ('') matches the home page, and maps
to the index view. The second pattern ('about/') matches the about page, and maps to the about view.
The third pattern ('contact/') matches the contact page, and maps to the contact view.
Once the requested URL is mapped, Django will move to views.py file and call a view (Function ),
which takes a web request and returns a web response. And the response back to the user.
Here's a simplified explanation of how URL mapping to views works in a web framework:
1. Define URL patterns: Developers specify the URLs that their application will respond to and define
corresponding view functions or classes to handle those URLs. This is usually done using a routing
configuration file or decorators in the code.
2. Map URLs to views: Each URL pattern is mapped to a specific view function or class that will handle
requests to that URL. This mapping is established either through configuration settings or by using
routing decorators provided by the web framework.
8
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
3. Handle requests: When a user makes a request to a specific URL, the web framework's router examines
the URL against the defined URL patterns and determines which view function or class should handle
the request.
4. Execute view logic: Once the appropriate view function or class is identified, the framework executes
the code within that view to generate the response. This typically involves fetching data from the
backend (model), processing it, and rendering it using an HTML template.
5. Return response: The view generates an HTTP response containing the HTML content to be displayed
to the user, which is then sent back to the user's browser.
9
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
In Django, mapping URLs to views is done through the urls.py module within each Django app.
Here's a basic overview of how it works:
1. Create a Django App: First, create a Django app or use an existing one where you want to define
your views and URL patterns.
2. Define Views: Write view functions or classes within your Django app. These views are Python
functions or classes that handle incoming HTTP requests and return HTTP responses. Views can be
as simple as returning a static HTML page or as complex as fetching data from a database and
rendering it using templates.
3. Map URLs to Views: In the urls.py module of your app, define URL patterns using Django's URL
patterns syntax. Each URL pattern is associated with a specific view function or class. You can use
regular expressions or simple strings to define URL patterns.
# myapp/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')), # Includes the URLs of the 'myapp' app
]
10
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
URLconfs in Django are Python modules that define the mapping between URLs and view functions.
They serve as a central mechanism for routing incoming HTTP requests to the appropriate view
functions or classbased views. Here's how they work:
1. URL Patterns: URL confs consist of a collection of URL patterns, each of which associates a URL
pattern (expressed as a regular expression or a simple string) with a view function or class.
2. Regular Expression Matchers: Django's URL dispatcher uses regular expression matching to
determine which view function should handle an incoming request based on the requested URL. When
a request comes in, Django compares the URL against each URL pattern in the URLconf until it finds
a match.
3. Modular Structure: URLconfs can be organized hierarchically, allowing you to include other
URLconfs using the include() function. This modular structure helps in breaking down URL
configurations into smaller, more manageable components.
4. Named URL Patterns: URL patterns can be given names, making it easier to reference them in
templates or view functions using the {% url %} template tag or the reverse() function.
5. Namespacing: URLconfs support namespacing, which allows you to differentiate between URLs
with the same name in different parts of your project. This is particularly useful in large projects with
multiple apps.
LOOSE COUPLING:
Loose coupling is a software design principle that promotes independence and modularity by
minimizing the dependencies between different components of a system. In the context of Django,
loose coupling is achieved through:
2. Decoupled URLs and Views: In Django's URL routing system, views are decoupled from URLs.
Views are Python functions or class-based views that encapsulate the logic for processing requests
11
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
and generating responses. URLconfs define the mapping between URLs and views but do not directly
reference the view functions themselves.
There are multiple packages for developer’s use. These packages may/ may not come in your use-
case. For the matter, the 1st package we are going to discuss is for those developers who are writing
their own Python scripts. These developers customize Django at a low level.
12
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
1. django.core.exceptions Package:
This package provides us with low-level exceptions. It enables us to define new rules for our
Django project. We can load models, views in our own defined ways. This module has use-cases
like: ● When you are working on a custom middleware.
● When making some changes to Django ORM.
AppRegistryNotReady: Imagine you're opening a new store, and before you can start selling
products, you need to set up your store's inventory system. However, you try to access the
inventory list before it's fully set up. This error occurs because the inventory system isn't
ready yet, similar to how in Django, the app registry isn't ready before Django completes its
app-loading process.
ObjectDoesNotExist: This error is like asking for a specific book in a library, but it's not in
the catalog. For example, you ask the librarian for a book titled "Python Programming" by
"John Smith", but the librarian can't find it. Similarly, in Django, if you try to access an
object that doesn't exist in the database, you'll get this error.
EmptyResultSet: Imagine you're searching for a specific item in your room, like your
favorite pen, but it's nowhere to be found. Similarly, in Django, if you perform a database
query expecting results but the query doesn't return anything, you'll get this error.
FieldDoesNotExist: Suppose you're organizing your wardrobe and looking for a specific
shirt color, like "green stripes", but you realize you don't have any shirts with that description.
Similarly, in Django, if you try to access a field in a model that doesn't exist, you'll get this
error.
MultipleObjectsReturned: Imagine you're searching for a unique key in your drawer, like
your house key, but you find two identical keys. This is similar to Django raising this
exception when you expect a database query to return a single object, but it returns more than
one.
SuspiciousOperation: Think of this as your home security system detecting unusual activity,
like someone trying to enter your house with the wrong key. In Django, if there's suspicious
13
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
behavior detected, such as a modification in session data or CSRF token, this exception is
raised to alert you about potential security threats.
PermissionDenied: Think of this as trying to access a restricted area without proper authorization,
like trying to enter a VIP section at a concert without the right pass. Similarly, in Django, if static files
are stored in an inaccessible directory, Django raises this error to prevent unauthorized access.
ViewDoesNotExist: Imagine you're trying to find a specific store in a mall, but it's no longer
there or the directory is outdated. Similarly, in Django, if a URL or view function doesn't
exist or can't be loaded, Django raises this error, often due to changes in the frontend design
or faulty URLs.
MiddlewareNotUsed: Think of this as having extra tools in your toolbox that you never use,
like carrying around a tool you don't need for your project. Similarly, in Django, if an unused
middleware is present in the configuration, Django raises this exception to alert you about
unnecessary middleware that could impact performance.
ImproperlyConfigured: Imagine trying to start a car with the wrong key or missing parts.
Similarly, in Django, if there are incorrect settings or modules that fail to load properly in the
main settings file, Django raises this error to indicate misconfigurations that need fixing.
FieldError: Consider organizing your closet but mistakenly putting two identical shirts in
the same slot, causing confusion. Similarly, in Django models, if there are errors like
duplicate field names or incorrect usage of methods, Django raises this error to prevent
confusion and ensure proper model structure.
14
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
4. Http Exceptions
We used this class in our first views. The HttpResponse is a sub-class of django.http class. The
module provides some exceptions and special responses.
UnreadablePostError - This exception occurs when a user uploads a corrupt file or cancels an
upload. In both cases, the file received by the server becomes unusable.
5. Transaction Exceptions
A transaction is a set of database queries. It contains the smallest queries or atomic queries. When
an error occurs at this atomic level, we resolve them by the django.db.transaction module. There
15
Dept of CSE, KNSIT
FULLSTACK DEVELOPMENT 21CS62
are errors like TransactionManagementError for all transaction-related problems with the
database.
6. Python Exceptions
Django is a Python framework. Of course, we get all the pre-defined exceptions of Python as
well. Python has a very extensive library of exceptions. And, you can also add more modules
according to use-case.
In this example:
Now, when a user visits a URL like /post/123/, Django captures the value 123 as the post_id parameter
and passes it to the post_detail view function. This allows you to dynamically display the details of
the blog post with ID 123.
Wildcard patterns make your URLs more flexible and allow you to handle dynamic content in your
Django applications easily. They're commonly used in various scenarios such as viewing specific user
profiles, accessing product details in an e-commerce site, or displaying article content on a news
website.
16
Dept of CSE, KNSIT