FSD MOD 1 Notes - MVC
FSD MOD 1 Notes - MVC
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.
1.Web Frameworks:
A web framework is a software framework designed to aid in the development of web applications
by providing reusable code, components, and tools that streamline the process. Web frameworks
typically follow the model-view-controller (MVC) architecture or a similar pattern, which helps
in organizing code and separating concerns.
Examples:
1. Django (Python)
2. Flask (Python)
3. Ruby on Rails (Ruby)
4. Express.js (JavaScript/Node.js)
5. ASP.NET Core (C#)
2. MVC Design Pattern
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.
● 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.
3.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.
4.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.
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.
Django also allows us to capture parts of the URL and pass them as arguments to the view function.
We can capture parts of the URL by placing them inside parentheses in the URL pattern. For
example, the following URL pattern captures an integer id from the URL:
path('post/<int:id>/', views.post_detail, name='post_detail'),
In this example, the view function views.post_detail() takes an integer id as an argument.
5.VIEWS
Once Django has found a matching URL pattern, it calls the associated view function. A view
function takes a request as its argument and returns an HTTP response. The response can be a
simple text message, an HTML page, or a JSON object.
example of a simple view function:
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello, world!')
In this example, the index view function takes a request object as its argument and returns an HTTP
response with the message "Hello, world!"
6.URLConf
Mapping URLS to views
➢ A URLconf is like a table of contents for your Django-powered Web site. Basically, it’s a
mapping between URL patterns and the view functions that should be called for those URL
patterns. It’s how you tell Django, “For this URL, call this code, and for that URL, call that
code.”
➢ When we execute the django-admin.py startproject , URLConf is created automatically
(urls.py.)
# Example:
# (r'^mysite/', include('mysite.apps.foo.urls.foo')),
# (r'^admin/', include('django.contrib.admin.urls')),
)
✓ The first line imports all objects from the django.conf.urls.defaults module, including a
function called patterns.
✓ The second line calls the function patterns() and saves the result into a variable called
urlpatterns. The patterns() function gets passed only a single argument—the empty string
✓ Urlpatterns – variable , which Django expects to find in your ROOT_URLCONF module.
This variable defines the mapping between URLs and the code that handles those URLs.
urlpatterns = patterns('',
(r'^time/$', current_datetime),
First, we imported the current_datetime view from its module (mysite/views.py, which translates
into mysite.views in Python import syntax). Next, we added the line (r'^time/$', current_datetime),.
This line is referred to as a URLpattern—it’s a Python tuple in which the first element is a simple
regular expression and the second element is the view function to use for that pattern
The caret character (^) and dollar sign character ($) are important. The caret means “require that
the pattern matches the start of the string,” and the dollar sign means “require that the pattern
matches the end of the string
6.REGULAR EXPRESSIONS
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django
URLconfs allow arbitrary regexes for powerful URL-matching capability,
Symbol Matches
The command python manage.py runserver imports a file called settings.py from the same
directory. This file contains all sorts of optional configuration for this particular Django instance,
but one of the most important settings is ROOT_URLCONF. The ROOT_ URLCONF setting tells
Django which Python module should be used as the URLconf for this Web site.
When a request comes in—say, a request to the URL /time/—Django loads the URLconf pointed
to by the ROOT_URLCONF setting. Then it checks each of the URLpatterns in that URLconf in
order, comparing the requested URL with the patterns one at a time, until it finds one that matches.
When it finds one that matches, it calls the view function associated with that pattern, passing an
HttpRequest object as the first parameter to the function.
The view function is responsible for returning an HttpResponse object.
When an HTTP request comes in from the browser, a server-specific handler constructs the
HttpRequest passed to later components and handles the flow of the response processing.
The handler then calls any available Request or View middleware. These types of middleware are
useful for augmenting incoming HttpRequest objects as well as providing special handling for
specific types of requests. If either returns an HttpResponse, processing bypasses the view.
8.URLconfs and Loose Coupling
In a Django Web application, the URL definitions and the view functions they call are loosely
coupled; that is, the decision of what the URL should be for a given function, and the
implementation of the function itself, reside in two separate places. This lets a developer switch
out one piece without affecting the other.
For example, consider the view function we wrote earlier, which displays the current date and time.
If we wanted to change the URL for the application— say, move it from /time/ to /currenttime/—
we could make a quick change to the URLconf, without having to worry about the underlying
implementation of the function. Similarly, if we wanted to change the view function—altering its
logic somehow—we could do that without affecting the URL to which the function is bound.
Furthermore, if we wanted to expose the current-date functionality at several URLs, we could
easily take care of that by editing the URLconf, without having to touch the view code
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:
distinct components, such as models, views, templates, and URLconfs. Each component has a
specific
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 and generating responses. URLconfs define the mapping between URLs and views but
do not directly reference the view functions themselves.
3. Dependency Injection: Django's design promotes dependency injection, allowing
components to be loosely coupled by injecting dependencies rather than directly instantiating
them. For example, views can accept parameters representing dependencies such as models, forms,
or services, making them easier to test and reuse.
1. django.core.exceptions Package
This package provides us with low-level exceptions. It enables us to define new rules for our
Django project.
2.Database Exceptions
We can import these exceptions from django.db module. The idea behind this implementation is:
Django wraps the standard database exceptions. And, when it happens, our Python code can
correspond with
the database exception. That makes it easy to deal with database exceptions in Python at a certain
level.
The exception wrappers provided by Django work in the same way as Python database API.
● InterfaceError
● DatabaseError
● DataError
● IntegrityError
● InternalError
● ProgrammingError
● NotSupportedError
3. 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.
4.404 Errors
when a different URL is requested
when we run the Django development server and hitting a page such as
http://127.0.0.1:8000/hello/ or http://127.0.0.1:8000/does-not-exist/, or even http://
127.0.0.1:8000/ (the site “root”). You should see a “Page not found” message (see Figure 3-2).
(Pretty, isn’t it? We Django people sure do like our pastel colors.) Django displays this message
because you requested a URL that’s not defined in your URLconf.
10.Wildcard URLpatterns
passing that data to the view function, so that we can use a single view function for any arbitrary
hour offset. (r'^time/plus/(\d{1,2})/$', hours_ahead),