FSD Module 1 Notes Full Stack Development Django
FSD Module 1 Notes Full Stack Development Django
Full-stack development refers to development of both the front-end (client-side) and back-end (server-side)
components of a web application.
Back-end Development:
Backend Development refers to the server-side development of the web application. It is the part of the
application where the server and database reside and the logics is build to perform operations.
Model Layer: Define data models using Django's Object-Relational Mapping (ORM) system. Models
represent the structure of the application's data and interact with the database.
View Layer: Implement views, which are Python functions or classes responsible for processing incoming
HTTP requests, interacting with the database through models, and returning HTTP responses.
Controller (Business Logic): Django's views act as controllers in the MVC pattern, handling the business
logic of the application by processing requests, validating input, and generating responses.
URL Routing: Define URL patterns in the URLconf (URL configuration) to map incoming URLs to
views. Django's URL routing mechanism allows for clean and flexible URL patterns.
Middleware: Implement middleware components to process requests and responses at various stages of
the Django request/response cycle. Middleware can perform tasks such as authentication, session
management, and error handling.
Front-end Development:
Front-end Development is the development or creation of a user interface using some markup languages and
other tools. It is basically the development of the user side where only user interaction will be counted.
Fullstack Development(21CS62)
Templates: Create HTML templates using Django's template engine, which allows for the dynamic
generation of HTML content based on data provided by views.
Static Files Handling: Serve static files (e.g., CSS, JavaScript, images) using Django's built-in static files
handling capabilities. Static files are typically stored in the project's static directory.
Integration with Front-end Frameworks: Optionally integrate Django with front-end frameworks like
React.js, Vue.js, or Angular for building rich, interactive user interfaces. Django can serve as a RESTful
API backend while the front-end framework handles the UI rendering and user interactions.
Database Interaction:
Django supports multiple databases including PostgreSQL, MySQL, SQLite, and Oracle. Developers can
define database models using Django's ORM and perform database operations such as querying, inserting,
updating, and deleting records.
#!/usr/bin/python import
MySQLdb
Fullstack Development(21CS62)
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
In this code First, it prints a “Content-Type” line, followed by a blank line, as required by CGI.
It prints some introductory HTML, connects to a database, and executes a query that
retrieves the latest ten books. Looping over those books, it generates an HTML unordered
list. Finally, it prints the closing HTML and closes the database connection.
The passage discusses the limitations of writing web applications from scratch using basic CGI scripts in
Python. It highlights the issues that arise as the application grows more complex, such as code
duplication, productivity reduction due to boilerplate code, environment-specific configurations, and the
need for separation of concerns between logic and presentation. These challenges are addressed by using
web frameworks like Django, which provide a structured programming environment, handle common
tasks, and promote clean, maintainable code.
Fullstack Development(21CS62)
The Model-View-Controller (MVC) design pattern is a software architectural pattern commonly used for
developing user interfaces. It divides an application into three interconnected components to separate internal
representations of information from the ways that information is presented and accepted by the user.
1. Model: This represents the application's data and business logic. It is responsible for managing the
application's data, responding to queries about the state of the application, and responding to instructions
to change the state of the application.
2. View: This represents the application's presentation layer. It is responsible for displaying the data provided
by the model in a particular format, and for accepting user input and passing it on to the controller.
3. Controller: This acts as an intermediary between the model and the view. It listens to user input and
invokes the corresponding actions on the model, potentially updating the view as a result. It also handles
any input validation and other application logic.
Separation of Concerns: Each component focuses on a specific aspect of the application, which makes
the codebase easier to understand, maintain, and test.
Modularity: Because each component is separate, it's easier to make changes to one part of the application
without affecting the others.
Reusability: Components can be reused in different parts of the application or even in different projects.
Example that demonstrates the difference between the previous approach and that undertaken using a
Web framework. Here’s how you might write the previous CGI code using Django:
# models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField()
def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render(request, 'latest_books.html', {'book_list': book_list})
Fullstack Development(21CS62)
# urls.py (the URL configuration)
from django.urls import path
from . import views
urlpatterns = [
path('latest/', views.latest_books),
]
The provided code snippets illustrate the overall design of a web application using Django, emphasizing the
separation of concerns. Here's a breakdown of the key components and their roles:
models.py: Defines the database structure using Python classes known as models. This component allows
for creating, retrieving, updating, and deleting records in the database without directly writing SQL
queries.
views.py: Contains the business logic of the application, encapsulated within functions or classes. In this
case, the latest_books() function is responsible for handling the logic associated with displaying the latest
books.
urls.py: Specifies the URL patterns and maps them to the corresponding views. This file determines which
view function is invoked for a particular URL pattern. For example, the URL /latest/ is associated with the
latest_books() view.
latest_books.html: An HTML template that defines the visual layout and presentation of the web page.
This file separates the design from the logic, allowing for easy modification of the user interface without
altering the underlying Python code.
Fullstack Development(21CS62)
These components adhere to the Model-View-Controller (MVC) design pattern, where the model represents the
data, the view handles the presentation layer, and the controller (in Django's case, the view functions) manages the
interaction between the model and the view.
Loose Coupling: Enables independent changes to different parts of the application. For instance,
developers can modify URLs without affecting the underlying logic, designers can adjust HTML templates
without touching the Python code, and database administrators can make changes to the database structure
with minimal impact on the application code.
3. Django’s History
Django's history illustrates its evolution from solving specific real-world challenges to becoming a versatile
and widely-used web development framework.
Fullstack Development(21CS62)
4. Django Architecture
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
Its architecture is based on the Model-View-Template (MVT) pattern, which is a slight variation of the Model-
View-Controller (MVC) pattern. Here is an overview of Django's architecture:
1. Model: The Model is responsible for the data access layer. It defines the data structure of the
application, typically mapping to the database. Models are defined as Python classes mapping
to the database. Models are defined as Python classes and use Django's ORM (Object-Relational Mapping) to
interact with the database.
Models: Represent and define the structure of your data (database schema).
ORM: Allows querying and manipulating the database using Python code instead of SQL.
2. View
The View is responsible for the business logic and interacting with the Model to retrieve data and pass it to the
appropriate Template. In Django, Views are Python functions or classes that take web requests and return web
responses.
Views: Handle user requests, fetch data from Models, and pass it to Templates.
Class-Based Views (CBV): Allow organizing views in a more object-oriented way.
3. Template
The Template is responsible for the presentation layer. It defines how the data should be displayed to the user.
Templates are HTML files with embedded Django Template Language (DTL) code that allows dynamic data
to be inserted into the HTML.
Templates: Define the layout and formatting of the data to be presented to the user.
Fullstack Development(21CS62)
Template Tags and Filters: Provide tools to manipulate and display data
Django:
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
It was designed to help developers take applications from concept to completion as quickly as possible.
2. MVC Pattern: Django follows the Model-View-Controller (MVC) architectural pattern, although it refers
to it as Model-View-Template (MVT). This helps separate the business logic from the user interface.
3. Admin Interface: Django includes a robust, built-in admin interface for managing application data, which
can be customized and extended.
4. ORM (Object-Relational Mapping): Django comes with an ORM that allows developers to interact with
databases using Python code instead of SQL, making database manipulation more intuitive.
5. Scalability: Django is designed to be scalable and can handle high traffic and large volumes of data.
6. Security: Django provides strong security features out of the box, including protection against SQL
injection, cross-site scripting, cross-site request forgery, and clickjacking. It also has a user authentication
system.
7. Form Handling: Django simplifies form handling by providing tools to create forms, validate data, and
display errors.
8. URL Routing: Django’s URL dispatcher allows you to design clean and maintainable URL patterns for
your application.
9. Template System: Django’s templating engine allows you to define HTML templates with placeholders for
dynamic content, making it easy to create dynamic web pages.
Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])
Page 8
lOMoARcPSD|34641734
Fullstack Development(21CS62)
10. Internationalization: Django supports internationalization, making it easy to create applications that can
handle multiple languages.
11. Extensibility: Django’s architecture is highly extensible, allowing developers to plug in third-party or custom
modules as needed.
1. Basic Structure: The urlpatterns variable is defined within urls.py, typically imported from
django.conf.urls.defaults. It's a list of tuples where each tuple contains a regular
expression pattern and the corresponding view function.
2. Defining URL Patterns: URL patterns are defined using regular expressions. For example,
(r'^time/$', current_datetime) maps the URL /time/ to the current_datetime
view function. The r before the string denotes a raw string in Python, which is useful for regular
expressions.
3. View Functions: View functions are referenced directly in the URLconf without calling them. This is
possible because functions are first-class objects in Python, meaning they can be passed around as
variables.
4. Caret (^) and Dollar Sign ($): These symbols are used in regular expressions to denote the start and
end of the string, respectively. They ensure that the URL pattern matches the entire URL and not just
a portion of it.
5. Appending Slash: Django automatically appends a slash to URLs. If a URL pattern expects a trailing
slash but is accessed without it, Django redirects the request to the version with the slash. This
behavior can be controlled using the APPEND_SLASH setting.
6. Testing Changes: To test changes made to the URLconf, start the Django development server using
python manage.py runserver. The server automatically reloads when Python code changes,
so there's no need to restart it between modifications.
Fullstack Development(21CS62)
URLconf is a fundamental part of Django development, allowing developers to define how URLs are mapped
to views in their applications. Understanding its structure and functionality is essential for building Django-
powered web applications efficiently.
Fullstack Development(21CS62)
Key Points
Configuration: settings.py and urls.py are automatically created when you start a new Django project.
ROOT_URLCONF in settings.py specifies the module to use for URL configuration.
URL Matching: Django processes URL patterns sequentially and uses regular expressions to match the
requested URL to a view function.
Fullstack Development(21CS62)
View Handling: When a URL pattern matches, the corresponding view function is called with an
HttpRequest object, and it must return an HttpResponse object.
When an HTTP request is received by a Django application, a series of steps involving handlers and
middleware takes place before a response is sent back to the client. Here's a summary of this process:
1. Request Handling:
o A server-specific handler constructs an HttpRequest object when a request is received.
o This HttpRequest object is then passed through a series of middleware components.
2. Middleware Processing:
o Request Middleware: Middleware in this category can modify the HttpRequest object or provide
special handling for certain types of requests. If any request middleware returns an HttpResponse,
the process skips the view function.
o View Middleware: Similar to request middleware, but it operates just before the view is called. It
can also short-circuit the process by returning an HttpResponse.
3. View Execution:
o If no middleware has returned a response, the appropriate view function is called based on the
URL routing. The view processes the request and generates an HttpResponse.
4. Exception Handling:
o If the view function raises an exception, control is transferred to the exception middleware.
o Exception Middleware: This middleware tries to handle exceptions. If it does not return an
HttpResponse, the exception is reraised.
o Django's default views provide user-friendly 404 (not found) and 500 (server error) responses if
no custom exception handling is provided.
5. Response Middleware:
o After the view (or exception middleware) generates an HttpResponse, response middleware is
applied.
o Response Middleware: This is used for any postprocessing of the HttpResponse before it is sent
back to the client. It can also be used for cleanup tasks specific to the request.
Fullstack Development(21CS62)
Key Points
HttpRequest Construction: The initial request object is created by the server-specific handler.
Middleware Types:
o Request Middleware: Enhances or processes the request before it reaches the view.
o View Middleware: Acts just before the view is called, can halt processing by returning a
response.
o Exception Middleware: Handles exceptions raised by the view, can provide custom responses.
o Response Middleware: Final processing before the response is sent to the client.
Exception Handling: Ensures that even when errors occur, Django can provide appropriate error
messages or fallback responses.
Process Flow
1. Incoming Request -> Request Middleware -> View Middleware -> View Execution -> Exception
Middleware (if needed) -> Response Middleware -> Outgoing Response
This structured flow ensures that requests are processed efficiently and that various aspects of the request and
response can be managed and modified by middleware at appropriate stages.
Fullstack Development(21CS62)
Fullstack Development(21CS62)
Loose coupling is a software development principle that emphasizes the independence of components. In a
loosely coupled system, changes in one component have minimal impact on others, promoting flexibility and
maintainability.
1. Flexibility: Easily change URLs without impacting view logic and vice versa.
2. Maintainability: Simplify updates and refactoring by isolating changes to specific parts of the code.
3. Reusability: Reuse view functions across different URLs without duplication.
7. 404 Errors
Django's handling of undefined URLs by displaying a "Page not found" message adheres to its
principle of clear and informative error reporting. You can further enhance user experience by
creating custom 404 error pages tailored to your application's design. This demonstrates Django's
flexibility and commitment to a clean, user-friendly web development framework.
Fullstack Development(21CS62)
Django's approach to handling undefined URLs showcases its commitment to clear and informative error
reporting. When a request is made to a URL not defined in the URLconf, Django responds with a "Page not
found" (404) message. This ensures users are promptly informed when they navigate to a non-existent page,
maintaining a user-friendly experience.
Key Points
Fullstack Development(21CS62)
o Creating a Custom Template: You can create a custom 404 error page by adding a
404.html template in your templates directory.
o Configuring Django: Ensure that the templates directory is correctly configured in
settings.py, and set DEBUG = False to see the custom error page in a production-
like environment.
8. Wildcard URLpatterns
Django URLconf to handle dynamic URL patterns using wildcards and implemented a view function that takes
parameters extracted from the URL. This functionality allows us to create more flexible and interactive web
applications.
urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)
Fullstack Development(21CS62)
html = "<html><body>In %s hour(s), it will be %s.</body></html>"
% (offset, dt)
return HttpResponse(html)
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
Using dynamic URL patterns and capturing URL data in Django allows developers to create more interactive
and flexible web applications. By handling different URLs with appropriate view functions and ensuring
proper error handling, Django maintains its principles of loose coupling and user-friendly error reporting.
Fullstack Development(21CS62)
crucial to ensure these detailed error pages are not exposed in production environments due to the sensitive
information they contain.
Key Points
o Visiting /time/plus/3/ would result in a "unsupported type for timedelta hours component: str"
error.
2. Understanding Django's Error Page:
o Exception Information: The error page displays the type of exception, a message, the file, and the
line number where the exception occurred.
o Python Traceback: A detailed traceback similar to Python’s standard traceback but more interactive.
It includes:
File name, function/method name, line number, and source code for each frame in the stack.
Ability to click on lines of source code to see surrounding lines for context.
"Local vars" link to view local variables and their values at the point where the exception
was raised.
o Copy-and-Paste View: An option to switch to a view of the traceback that is easier to copy and paste
for sharing with others.
o Request Information: Details about the incoming request, including GET and POST data, cookies,
and meta-information such as CGI headers.
Fullstack Development(21CS62)
o Settings Information: Lists all Django settings for the current installation.
3. Using the Debug Page for Debugging:
o Temporarily inserting an assert False statement in your view can trigger the error page,
allowing you to inspect local variables and program state without using print statements.
o Example:
4. Security Considerations:
o The debug page contains sensitive information about your code and configuration.
o It is only displayed when your Django project is in debug mode to prevent exposure in a production
environment.
o Every new Django project starts in debug mode automatically. We'll learn how to deactivate debug
mode later.
5. Restoring Functionality:
o After exploring the error page, uncomment the line to fix the view function: