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

FSD Module 1 Notes Full Stack Development Django

Uploaded by

Mohammed Yafis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

FSD Module 1 Notes Full Stack Development Django

Uploaded by

Mohammed Yafis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

lOMoARcPSD|34641734

FSD Module 1 Notes - Full stack development -Django

Full Stack Django (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by aarzu qadri ([email protected])
lOMoARcPSD|34641734

Sri Sai Vidya Vikas Shikshana Samithi ®

SAI VIDYA INSTITUTE OF TECHNOLOGY


Approved by AICTE, New Delhi, Affiliated to VTU, Recognized by Govt. of Karnataka
Accredited by NBA
RAJANUKUNTE, BENGALURU 560 064, KARNATAKA
Phone: 080-28468191/96/97/98 ,Email: [email protected], URLwww.saividya.ac.in

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CSE)

Module-1: MVC based Web Designing

Full stack web development

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.

Downloaded by aarzu qadri ([email protected])


lOMoARcPSD|34641734

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.

1. What Is a Web Framework?


A web framework often referred to as a web application framework is a pre-built set of libraries, software
tools, and best practices that support the overall software development of web apps. It handle multiple
routine tasks and proffer a structured way to organize code, making development more maintainable and
efficient.

Django is a prominent member of a new generation of Web frameworks.


For example, here’s a simple CGI script, written in Python, that displays the ten most
recently published books from a database:

#!/usr/bin/python import

MySQLdb

print "Content-Type: text/html"


print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')


cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT
10") for row in cursor.fetchall():

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 2
lOMoARcPSD|34641734

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.

2. The MVC Design Pattern


The MVC design pattern is a software architecture pattern that separates an application into three
main components: Model, View, and Controller, making it easier to manage and maintain the
codebase. It also allows for the reusability of components and promotes a more modular approach to
software development.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 3
lOMoARcPSD|34641734

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.

The key benefits of using the MVC pattern include:

 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()

# views.py (the business logic)


from django.shortcuts import render
from .models import Book

def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render(request, 'latest_books.html', {'book_list': book_list})

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 4
lOMoARcPSD|34641734

Fullstack Development(21CS62)
# urls.py (the URL configuration)
from django.urls import path
from . import views

urlpatterns = [
path('latest/', views.latest_books),
]

# latest_books.html (the template)


<html>
<head>
<title>Books</title>
</head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body>
</html>

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 5
lOMoARcPSD|34641734

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.

Advantages of this Approach:

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

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 6
lOMoARcPSD|34641734

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 7
lOMoARcPSD|34641734

Fullstack Development(21CS62)
 Template Tags and Filters: Provide tools to manipulate and display data

Fig: Django Architecture

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.

Key Features of Django:

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.

5. Mapping URLs to Views


URL conf in Django serves as a mapping between URL patterns and the corresponding view functions. When
you create a new Django project using django-admin.py startproject, a file named urls.py is
automatically generated. This file defines the urlpatterns variable, which determines how URLs are
routed to view functions.

Key points regarding URLconf:

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 9
lOMoARcPSD|34641734

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 10
lOMoARcPSD|34641734

Fullstack Development(21CS62)

5.1 How Django Processes a Request


Process that happens when you run the Django development server and make requests to web pages:

1. Starting the Server:


o The command python manage.py runserver is used to start the Django development server.
o This command imports the settings.py file from the same directory, which contains various
configuration settings for the Django instance.
2. Settings and URL Configuration:
o One critical setting in settings.py is ROOT_URLCONF, which tells Django which Python
module to use as the URLconf for the website.
o When you use django-admin.py startproject, it generates settings.py and urls.py. The
autogenerated settings.py file has a ROOT_URLCONF that points to the autogenerated urls.py.
3. Handling a Request:
o When a request is made, for example to /time/, Django loads the URLconf specified by the
ROOT_URLCONF setting.
o Django then processes the urlpatterns in the URLconf in order. It compares the requested URL
with each pattern one by one until it finds a match.
o
o Once a matching pattern is found, Django calls the associated view function, passing an
HttpRequest object as the first parameter.
4. View Functions and Responses:
o The view function handles the request and is responsible for returning an HttpResponse object,
which contains the response data for the client.

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 11
lOMoARcPSD|34641734

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.

5.2 How Django Processes a Request

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 12
lOMoARcPSD|34641734

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 13
lOMoARcPSD|34641734

Fullstack Development(21CS62)

Figure 3-1. The complete flow of a Django request and response

6. URLconfs and Loose Coupling


Django's use of URLconfs is a clear demonstration of the loose coupling principle.
By separating URL definitions from view implementations, Django promotes a flexible and
maintainable codebase.
This separation allows developers to make changes in one area (like URLs) without unintended
consequences in another (like view logic), leading to more robust and adaptable web applications.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 14
lOMoARcPSD|34641734

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.

URLconfs as an Example of Loose Coupling

In Django, URLconfs exemplify loose coupling. Here’s how:

1. Separate URL Definitions and View Functions:


o URL Definitions: URLs are defined in the urls.py file.
o View Functions: View functions reside in separate Python modules (e.g., views.py).
2. Independent Modification:
o Changing URLs: You can modify the URL pattern in urls.py without altering the view
function.
o Changing View Logic: You can change the logic in a view function without needing to
update the URL configuration.
3. Multiple URLs for a Single View:
o You can map multiple URLs to the same view function by adding multiple patterns in
urls.py.

Benefits of Loose Coupling

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 15
lOMoARcPSD|34641734

Fullstack Development(21CS62)

Figure 3-2. Django’s 404 page

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

1. Default 404 Error Handling:


o When a URL is requested that is not mapped in the URLconf, Django displays a default
"Page not found" message.
o This behavior ensures that users receive clear feedback when they attempt to access
undefined routes.
2. Testing Undefined URLs:
o By running the Django development server and visiting URLs such as
http://127.0.0.1:8000/hello/, http://127.0.0.1:8000/does-not-
exist/, or http://127.0.0.1:8000/, you can see the default 404 page in action.
3. Customizing the 404 Error Page:

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 16
lOMoARcPSD|34641734

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.

1. Defining Dynamic URL Patterns:


o We used regular expressions in our URLconf to capture dynamic parts of the URL. Specifically, we
used \d{1,2} to match one or two-digit numbers.
o Example of URL patterns:

urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)

2. Capturing URL Data:


o By placing parentheses around parts of the regular expression in the URL pattern, we capture that part
of the URL and pass it as a parameter to the view function.
o For instance, (r'^time/plus/(\d{1,2})/$', hours_ahead) captures the number in the
URL /time/plus/3/ and passes it to the hours_ahead view function.
3. Implementing the View Function:
o The hours_ahead view function takes the offset parameter, converts it to an integer, and
calculates the future time.
o Example view function:

from django.http import HttpResponse


import datetime

def hours_ahead(request, offset):


offset = int(offset)
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 17
lOMoARcPSD|34641734

Fullstack Development(21CS62)
html = "<html><body>In %s hour(s), it will be %s.</body></html>"
% (offset, dt)
return HttpResponse(html)

4. Handling Invalid URLs:


o If a URL does not match any pattern in the URLconf, Django returns a "Page not found" (404) error.
o For example, accessing /time/plus/100/ should return a 404 error since our URL pattern
restricts the offset to one or two digits.
5. Testing the URL Patterns and Views:
o By running the Django development server and visiting various URLs, we can verify that the
application behaves as expected.
o URLs like /time/plus/3/, /time/plus/24/ should work, while /time/plus/100/
should return a 404 error.
6. Complete views.py Example:
o The views.py file should now contain both the current_datetime and hours_ahead view
functions:

from django.http import HttpResponse


import datetime

def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

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)

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.

9. Django’s Pretty Error Pages


Understanding and utilizing Django's detailed error pages is essential for efficient debugging. The error pages
provide comprehensive information, making it easier to identify and resolve issues in your code. However, it's

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 18
lOMoARcPSD|34641734

Fullstack Development(21CS62)
crucial to ensure these detailed error pages are not exposed in production environments due to the sensitive
information they contain.

We intentionally introduced an error into our Django application to explore Django's


detailed error pages. Understanding how to interpret these error pages is crucial for
debugging and improving your development workflow.

Key Points

1. Deliberately Introducing an Error:


o We commented out a crucial line in the hours_ahead view to cause a TypeError:

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)

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.

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 19
lOMoARcPSD|34641734

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:

def hours_ahead(request, offset):


assert False # Triggers the debug page
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)

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:

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)

Dept. of CSE, SVIT Downloaded by aarzu qadri ([email protected])


Page 20

You might also like