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

FSD MOD 1 Notes - MVC

The document discusses the basics of MVC design pattern and Django web framework. It covers topics like web frameworks, MVC pattern, Django evolution, URL mapping, views, URL configurations and regular expressions. Key aspects of each component in MVC like model, view and controller are explained.

Uploaded by

apoorva.k2017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

FSD MOD 1 Notes - MVC

The document discusses the basics of MVC design pattern and Django web framework. It covers topics like web frameworks, MVC pattern, Django evolution, URL mapping, views, URL configurations and regular expressions. Key aspects of each component in MVC like model, view and controller are explained.

Uploaded by

apoorva.k2017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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.

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.)

from django.conf.urls.defaults import *

urlpatterns = patterns(' ',

# Example:

# (r'^mysite/', include('mysite.apps.foo.urls.foo')),

# Uncomment this for admin:

# (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.

Example program :current_date

from django.conf.urls.defaults import *

from mysite.views import current_datetime

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 r in r'^time/$' means that '^time/$ is a Python raw string.

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

. (dot) Any character


\d Any digit
[A-Z] Any character, A–Z (uppercase)
[a-z] Any character, a–z (lowercase)
[A-Za-z] Any character, a–z (case insensitive)
+ One or more of the previous character (e.g., \d+
matches one or more digit)
[^/]+ All characters until a forward slash (excluding the
slash itself)
? Zero or more of the previous character (e.g., \d*
matches zero or more digits)
{1,3} Between one and three (inclusive) of the previous
expression

7.How Django Processes a Request

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:

1. Separation of Concerns: Django encourages the separation of concerns by dividing an


application into

distinct components, such as models, views, templates, and URLconfs. Each component has a
specific

responsibility and interacts with other components through well-defined interfaces.

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.

4. Pluggable Applications: Django's app-based architecture encourages the development of


pluggable, reusable applications that can be easily integrated into different projects. By providing
well-defined APIs and extension points, Django promotes loose coupling between applications,
enabling greater flexibility and scalability.

9.Django Exceptions & Errors


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.

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.

list of exceptions provided by this package


1.1. AppRegistryNotReady This error occurs when the application model is imported before the
app-loading process. When Django project starts, it generates an application registry. It
contains the information in settings.py and some more custom settings. This registry will keep
record and install all the important components. This registry contains settings-config of all
apps inside INSTALLED_APPS. It is the first kernel of your Django project. To use any app
or submodule in your project, it has to load-in here first. It is useful in exception catching
when developing your own scripts. It may not occur when using default Django files.
1.2. 1.2. ObjectDoesNotExist This exception occurs when we request an object which does not
exist. It is the base class for all the DoesNotExist Errors. ObjectDoesNotExist emerges mainly
from get() in Django.
1.3. 1.3. EmptyResultSet This error is rare in Django. When we generate a query for objects and
if the query doesn’t return any results, it raises this error.
1.4. FieldDoesNotExist This one is clear from its name. When a requested field does not exist in a
model, this meta.get_field() method raises this exception
1.5. MultipleObjectsReturned When we expect a query to return a single response/ object but it
returns more than one object, then Django raises this exception.
1.6. SuspiciousOperation It is one of the security classes of Django. Django raises this error when
it has detected any malicious activity from the user. This exception has many subclasses which
are helpful in taking better security measures. When anyone modifies the session_data, Django
raises this exception. Even when there is a modification in csrf_token, we get this exception
1.7. PermissionDenied This exception is the clearest of all. You must have dealt with this exception
while working on static files. Django raises this error when we store our static files in a
directory which is not accessible

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.

The errors are:

● 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

from django.conf.urls.defaults import *


from mysite.views import current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/\d+/$', hours_ahead),
)
This URLpattern will match any URL such as /time/plus/2/, /time/plus/25/, or even
/time/plus/100000000000/

(r'^time/plus/\d{1,2}/$', hours_ahead), ---------limiting the offset to 99 hours

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),

def hours_ahead(request, offset):


offset = int(offset)
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset,
dt)
return HttpResponse(html)
The view function, hours_ahead, takes two parameters: request and offset.
offset is the string captured by the parentheses in the URLpattern. For example, if the requested
URL were /time/plus/3/, then offset would be the string '3'. If the requested URL were
/time/plus/21/, then offset would be the string '21'.
int() on offset. ---This converts the string value to an integer.

You might also like