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

fsd notes

The document provides an overview of Django, a high-level Python web framework that follows the Model-Template-View (MTV) architectural pattern, emphasizing its features such as ORM, URL routing, and security. It explains the MVC design pattern, its components, and how Django implements these concepts, including the organization of models, views, and URL configurations. Additionally, it discusses the evolution of Django from its origins to its current status as a widely used open-source framework for building dynamic web applications.

Uploaded by

amanchaudhary.ka
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)
4 views

fsd notes

The document provides an overview of Django, a high-level Python web framework that follows the Model-Template-View (MTV) architectural pattern, emphasizing its features such as ORM, URL routing, and security. It explains the MVC design pattern, its components, and how Django implements these concepts, including the organization of models, views, and URL configurations. Additionally, it discusses the evolution of Django from its origins to its current status as a widely used open-source framework for building dynamic web applications.

Uploaded by

amanchaudhary.ka
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/ 114

21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Module-01

MVC based Web Designing

Web Framework
Django: High-level Python web framework for rapid development. Features include an ORM,
URL routing, template engine, admin interface, and strong security. Best for large, database-
driven applications.

Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. It follows the model-template-view (MTV) architectural pattern, which is
similar to the model-view-controller (MVC) pattern used in other frameworks.

Key features of Django include:

1. ORM (Object-Relational Mapping): Django provides a powerful ORM that allows you
to interact with databases using Python code instead of raw SQL.
2. URL Routing: It uses a URL configuration file to map URLs to views, making it easy to
create clean, SEO-friendly URLs.
3. Template Engine: Django has a template language that allows you to separate the design
from Python code.
4. Forms: It offers a form framework that handles rendering forms, validating user input,
and processing submitted data.
5. Authentication and Authorization: Django comes with a robust user authentication
system out of the box.
6. Admin Interface: It automatically generates an admin interface for your models, which
is great for managing your site's content.
7. Security Features: Django provides protection against common web vulnerabilities like
XSS, CSRF, SQL injection, etc.

Search Creators... Page 1


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

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.

What is the 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.

How the MVC pattern works in general and how it can be related to Django in scope.

The MVC pattern is a software architecture pattern that separates data presentation from
the logic of handling user interactions (in other words, saves you stress:), it has been around as a
concept for a while, and has invariably seen an exponential growth in use since its inception. It has
also been described as one of the best ways to create client-server applications, all of the best
frameworks for web are all built around the MVC concept.

Search Creators... Page 2


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Model: This handles your data representation, it serves as an interface to the data stored in the
database itself, and also allows you to interact with your data without having to get perturbed with
all the complexities of the underlying database.

View: As the name implies, it represents what you see while on your browser for a web application
or In the UI for a desktop application.

Controller:
data i.e. it uses programmed logic to figure out what is pulled from the database through the model
and passed to the view, also gets information from the user through the view and implements the
given logic by either changing the view or updating the data via the model, To make it more
simpler, see it as the engine room.

Now that we understand the general concept of the MVC, understanding how it is implemented in
different frameworks can be another task as some frameworks (Django inclusive) like to
implement this same functionality in another way making it a bit difficult understanding what
actually happens at each layer.

How do we relate it to Our scope in Django?

implementation, the framework considers handling the Controller part of the MVC itself and
letting most of the good stuff happen in the Model-Template-View, this is why Django is mostly
referred to as the MTV framework.

Search Creators... Page 3


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

In the MTV pattern:

1. models.py (the database tables):

Defines the database model for a book using Django's models. Model class.
Contains a Book class with two fields: name (CharField) and pub_date (DateField).
Represents the data layer of the application

from django.db import models

class Book(models.Model):

name = models.CharField(max_length=50)

pub_date = models.DateField()

Search Creators... Page 4


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

2. views.py (the business logic):

Implements the latest_books() function as the view.


Retrieves the latest 10 books from the database and passes them to the template for
rendering.
Handles user requests and prepares data for display.

from django.shortcuts import render_to_response

from .models import Book

def latest_books(request):

book_list = Book.objects.order_by('-pub_date')[:10]

return render_to_response('latest_books.html', {'book_list': book_list})

3. urls.py (the URL configuration):

Defines URL patterns and maps them to corresponding views.


Specifies that the URL /latest/ should be handled by the latest_books() view.

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^latest/$', views.latest_books),

3. latest_books.html (the template):

HTML template for rendering the latest books.


Uses Django's template language to iterate over the book_list passed from the view and
display book names in a list.

Search Creators... Page 5


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

<html>

<head>

<title>Books</title>

</head>

<body>

<h1>Books</h1>

<ul>

{% for book in book_list %}

<li>{{ book.name }}</li>

{% endfor %}

</ul>

</body>

</html>

This Django program follows the Model-View-Controller (MVC) design pattern:

Model (models.py): Defines the database model.


View (views.py): Handles business logic and prepares data for display.
Controller (urls.py): Routes URLs to corresponding views.
Template (latest_books.html): Defines the presentation layer and renders data to the user.

The components are loosely coupled, allowing for independent changes and enhancing
maintainability and scalability of the application.

Search Creators... Page 6


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Django Evolution

1. Origins: Django was created by Adrian Holovaty and Simon Willison in the fall of 2003.
They were web programmers at the Lawrence Journal-World newspaper in Lawrence,
Kansas, USA.

2. Development Environment: The team worked in a fast-paced environment with tight


journalism deadlines. They needed to build and maintain web applications quickly and
efficiently.

3. Organic Growth: Django grew organically from the real-world needs of the development
team. They initially built applications from scratch but soon realized the need for a
framework to streamline their process.

4. Framework Creation: Following the typical path of many web developers, the team
started refactoring their code to share common functionalities across applications. This led
to the creation of a framework.

5. Open-Source Release: In the summer of 2005, after developing the framework to a usable
state, the team, including Jacob Kaplan-Moss, decided to release it as open source software
in July 2005.

6. Name Origin: The framework was named Django after the jazz guitarist Django
Reinhardt.

7. Current Status: Today, Django is a well-established open-source project with a large


community of users and contributors worldwide. Adrian Holovaty and Jacob Kaplan-Moss,
two of the original developers, still provide guidance for its growth, but it's now a
collaborative effort.

Search Creators... Page 7


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

8. Sweet Spot: Django's origins in a news environment influenced its design, making it
particularly well-suited for content sites with dynamic, database-driven information.
However, it's effective for building a wide range of dynamic websites.

Version Date Description

0.90 16 Nov 2005

0.91 11 Jan 2006 magic removal

0.96 23 Mar 2007 newforms, testing tools

1.0 3 Sep 2008 API stability, decoupled admin, unicode

1.1 29 Jul 2009 Aggregates, transaction based tests

1.2 17 May 2010 Multiple db connections, CSRF, model validation

1.3 23 Mar 2011 Timezones, in browser testing, app templates.

1.5 26 Feb 2013 Python 3 Support, configurable user model

1.6 6 Nov 2013 Dedicated to Malcolm Tredinnick, db transaction management,


connection pooling.

1.7 2 Sep 2014 Migrations, application loading and configuration.

1.8 LTS 2 Sep 2014 Migrations, application loading and configuration.

1.8 LTS 1 Apr 2015 Native support for multiple template engines.Supported until
at least April 2018

1.9 1 Dec 2015 Automatic password validation. New styling for admin
interface.

1.10 1 Aug 2016 Full text search for PostgreSQL. New-style middleware.

1.11 LTS 1.11 LTS Last version to support Python 2.7.Supported until at least April
2020

Search Creators... Page 8


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

2.0 Dec 2017 First Python 3-only release, Simplified URL routing syntax,
Mobile friendly admin.

Views, Mapping URL to Views

View Creation (views.py):

In Django, views are Python functions that handle web requests and return web responses.
The views.py file is a convention for organizing view functions within a Django project.
To create a view, you define a Python function that takes an HttpRequest object as its first
parameter and returns an HttpResponse object.
In the provided example, the hello view function simply returns an HttpResponse object
with the text "Hello world".

# views.py

from django.http import HttpResponse

def hello(request):

return HttpResponse("Hello world")

Explanation:

Import the HttpResponse class from django. http module.


Define a function named hello which will be the view.
The view function takes a request parameter (an instance of HttpRequest), although it
doesn't use it here.
The view returns an HttpResponse object containing the text "Hello world".

URL Configuration (urls.py):

Django uses a URLconf (URL configuration) to map URLs to view functions.


The urls.py file is where you define the URL patterns for your Django project.

Search Creators... Page 9


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

In the URLconf, you import the view functions from views.py and map them to specific
URLs using regular expressions.
Each URL pattern is defined as a tuple containing a regular expression pattern and the
corresponding view function.
In the provided example, the URL pattern r'^hello/$' maps to the hello view function,
indicating that the view should be invoked when the URL /hello/ is requested.

# urls.py

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^hello/$', views.hello),

Explanation:

Import necessary modules and the hello view function from views.py.
Define the urlpatterns variable, which is a mapping between URLs and the view functions.
Map the URL /hello/ to the hello view function. When a user visits this URL, Django will
call the hello function.

This setup tells Django to display "Hello world" when a user navigates to the /hello/ URL in the
browser.

Request Handling:

When a user makes a request to the Django server, Django's URL resolver examines the
requested URL and determines which view function to call based on the URLconf.
The view function receives an HttpRequest object as its first parameter, which contains
metadata about the request (e.g., headers, user agent, request method).
Although the hello view function doesn't utilize the HttpRequest object in this example, it's
a standard parameter for all view functions in Django.

Search Creators... Page 10


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Response Generation:

View functions in Django are responsible for generating web responses.


In the provided example, the hello view function returns an HttpResponse object containing
the string "Hello world".
Django's HttpResponse class allows you to create HTTP responses with custom content
(e.g., HTML, JSON) and status codes.

URL Mapping:

URL patterns defined in the URLconf serve as a mapping between URLs and view
functions.
Django uses regular expressions to match incoming URLs to patterns defined in the
URLconf.
When a matching URL is found, Django calls the corresponding view function to handle
the request and generate the response.

Working of Django URL Confs and Loose Coupling

In a dynamic web application, URLs often contain parameters that influence the output of the page.
To demonstrate this, let's create a view in Django that displays the current date and time offset by
a certain number of hours. Instead of creating separate views for each hour offset, which would
clutter the URLconf, we can use a single view with a parameter in the URL to specify the hour
offset dynamically.

Search Creators... Page 11


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

View Function:

We'll create a single view function named offset_datetime, which takes an hour offset as a
parameter and returns the current date and time offset by that number of hours.

# views.py

from django.http import HttpResponse

from datetime import datetime, timedelta

def offset_datetime(request, offset):

try:

offset_hours = int(offset)

dt = datetime.now() + timedelta(hours=offset_hours)

return HttpResponse(f"Current date/time offset by {offset_hours} hours: {dt}")

except ValueError:

return HttpResponse("Invalid offset")

2. URL Configuration:

We'll define a dynamic URL pattern with a parameter to specify the hour offset.

# urls.py

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^time/plus/(?P<offset>\d+)/$', views.offset_datetime),

Search Creators... Page 12


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Explanation:

The URL pattern r'^time/plus/(?P<offset>\d+)/$' matches URLs like /time/plus/1/,


/time/plus/2/, etc., where the offset parameter specifies the number of hours to add to the
current date/time.
The (?P<offset>\d+) part of the pattern captures the value of the offset parameter as a string
of digits and passes it to the offset_datetime view function.

Loose coupling is a fundamental principle in software development, and Django's URLconfs


provide a clear example of its application within the framework. Here's a breakdown of how
URLconfs and views demonstrate loose coupling in Django:

Definition Separation:

In Django, URLconfs are used to map URLs to view functions, specifying which view
function should be called for a given URL pattern.
The URL definitions and the implementation of view functions are kept separate, residing
in two distinct places within the Django project.

Interchangeability:

Loose coupling ensures that changes made to one component have minimal impact on
others.
If two pieces of code are loosely coupled, modifications to one piece won't require changes
to the other, promoting flexibility and maintainability.

Flexibility in Changes:

With Django's URLconfs, you can modify URL patterns without affecting the view
functions they map to, and vice versa.
For example, changing the URL pattern for a view (e.g., moving from /time/ to /current-
time/) can be accomplished without altering the view function itself.
Similarly, modifications to the view function's logic can be made independently of URL
changes.

Search Creators... Page 13


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Scalability:

Loose coupling enables easy scaling and extension of functionality within a Django project.
Adding new URLs or modifying existing ones can be done without disrupting other parts
of the application.
For instance, exposing a view function at multiple URLs can be achieved by editing the
URLconf without touching the view code.

Maintainability:

Separating URL definitions and view implementations promotes code clarity and makes it
easier to understand and maintain the project.
Developers can focus on specific tasks (e.g., URL routing or view logic) without needing
extensive knowledge of other components.

By leveraging loose coupling, Django enables developers to build web applications that are
flexible, modular, and easy to maintain.

This approach aligns with Django's philosophy of promoting rapid development and scalability
while ensuring code robustness and maintainability.

Errors in Django

When you deliberately introduce a Python error into your Django project, such as commenting out
critical lines of code, Django's error handling mechanisms come into play. Let's delve into how
Django's error pages help you debug and understand the issue:

Error Introduction:

By commenting out crucial lines of code in a view function, you intentionally introduce a
Python error into your Django project.

Search Creators... Page 14


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Error Page Display:

When you navigate to a URL that triggers the error, Django displays a detailed error page
with significant information about the exception.
At the top of the error page, Django presents key information about the exception,
including the type of exception, parameters, file name, and line number where the
exception occurred.
Additionally, Django provides the full Python traceback for the exception, displaying each
level of the stack trace along with the corresponding file, function/method name, and line
number.

Interactive Traceback:

Django's error page offers an interactive traceback, allowing you to click on any line of
source code to view several lines before and after the erroneous line, providing context for
better understanding.
You can also click on "Local vars" under any frame in the stack to view a table of all local
variables and their values at the exact point where the exception was raised, aiding in
debugging.

Sharing and Debugging:

Django offers options to easily share the traceback with others for technical support. You
can switch to a copy-and-paste view or share the traceback on a public website like
http://www.dpaste.com/.
Additionally, the error page includes information about the incoming web request (GET
and POST data, cookies, CGI headers) and Django settings, helping you identify the
context of the error.

Debugging Aid:

Developers accustomed to debugging with print statements can leverage Django's error
page for debugging purposes by inserting an assert False statement at any point in the view
function to trigger the error page and inspect the local variables and program state.

Search Creators... Page 15


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Security Considerations:

It's essential to recognize that the information displayed on Django's error page is sensitive
and should not be exposed on the public internet. Django only displays the error page when
the project is in debug mode, which is automatically activated during development but
should be deactivated in production to prevent potential security risks.

By utilizing Django's error pages effectively, developers can gain valuable insights into
runtime errors, facilitate debugging, and ensure the robustness of their Django applications.

Wild Card patterns in URLS

Wildcard patterns, also known as catch-all patterns or wildcard segments, are a useful feature in
Django's URL routing system. They allow you to capture any part of a URL and pass it as a
parameter to a view function. Here's how wildcard patterns work in Django's URL configuration:

Basic URL Patterns:

In Django, URL patterns are defined using regular expressions (regex) in the URLconf
module (urls.py).
Typically, URL patterns match specific URLs and route them to corresponding view
functions.

Wildcard Patterns:

Wildcard patterns allow you to capture variable parts of a URL and pass them as parameters
to view functions.
The most common wildcard pattern in Django's URL routing system is the
(?P<parameter_name>pattern) syntax, where parameter_name is the name of the parameter
and pattern is a regex pattern that matches the parameter value.
This syntax captures the matched part of the URL and passes it as an argument to the
associated view function.

Search Creators... Page 16


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Usage Example:

Let's say you want to create a dynamic URL pattern for displaying details of a specific
item. Instead of creating separate URL patterns for each item, you can use a wildcard
pattern to capture the item's identifier from the URL.

Example:

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('item/<int:item_id>/', views.item_detail),

In this example, <int:item_id> is a wildcard pattern that captures an integer value from the
URL and passes it as the item_id parameter to the item_detail view function.

Parameter Naming:

When using wildcard patterns, it's important to give meaningful names to the captured
parameters to improve code readability.
Parameter names are enclosed in angle brackets (< >) and must be valid Python variable
names.

Wildcard Segment:

Django also supports wildcard segments in URL patterns, denoted by an asterisk (*), which
captures the remainder of the URL as a single parameter.
Wildcard segments are useful for creating catch-all patterns to handle dynamic routes.

Search Creators... Page 17


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Usage Example with Wildcard Segment:

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('blog/<slug:category>/', views.blog_category),

path('blog/<slug:category>/<path:remainder>/', views.blog_post),

In this example, <path:remainder> is a wildcard segment that captures the remaining part
of the URL as a single parameter, allowing for dynamic handling of blog posts with
variable URLs.

Wildcard patterns in Django's URL routing system provide flexibility and enable the creation of
dynamic and expressive URL patterns, making it easier to build robust and scalable web
applications

Search Creators... Page 18


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Module-01

MVC based Web Designing

Web Framework
Django: High-level Python web framework for rapid development. Features include an ORM,
URL routing, template engine, admin interface, and strong security. Best for large, database-
driven applications.

Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. It follows the model-template-view (MTV) architectural pattern, which is
similar to the model-view-controller (MVC) pattern used in other frameworks.

Key features of Django include:

1. ORM (Object-Relational Mapping): Django provides a powerful ORM that allows you
to interact with databases using Python code instead of raw SQL.
2. URL Routing: It uses a URL configuration file to map URLs to views, making it easy to
create clean, SEO-friendly URLs.
3. Template Engine: Django has a template language that allows you to separate the design
from Python code.
4. Forms: It offers a form framework that handles rendering forms, validating user input,
and processing submitted data.
5. Authentication and Authorization: Django comes with a robust user authentication
system out of the box.
6. Admin Interface: It automatically generates an admin interface for your models, which
is great for managing your site's content.
7. Security Features: Django provides protection against common web vulnerabilities like
XSS, CSRF, SQL injection, etc.

Search Creators... Page 1


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

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.

What is the 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.

How the MVC pattern works in general and how it can be related to Django in scope.

The MVC pattern is a software architecture pattern that separates data presentation from
the logic of handling user interactions (in other words, saves you stress:), it has been around as a
concept for a while, and has invariably seen an exponential growth in use since its inception. It has
also been described as one of the best ways to create client-server applications, all of the best
frameworks for web are all built around the MVC concept.

Search Creators... Page 2


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Model: This handles your data representation, it serves as an interface to the data stored in the
database itself, and also allows you to interact with your data without having to get perturbed with
all the complexities of the underlying database.

View: As the name implies, it represents what you see while on your browser for a web application
or In the UI for a desktop application.

Controller:
data i.e. it uses programmed logic to figure out what is pulled from the database through the model
and passed to the view, also gets information from the user through the view and implements the
given logic by either changing the view or updating the data via the model, To make it more
simpler, see it as the engine room.

Now that we understand the general concept of the MVC, understanding how it is implemented in
different frameworks can be another task as some frameworks (Django inclusive) like to
implement this same functionality in another way making it a bit difficult understanding what
actually happens at each layer.

How do we relate it to Our scope in Django?

implementation, the framework considers handling the Controller part of the MVC itself and
letting most of the good stuff happen in the Model-Template-View, this is why Django is mostly
referred to as the MTV framework.

Search Creators... Page 3


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

In the MTV pattern:

1. models.py (the database tables):

Defines the database model for a book using Django's models. Model class.
Contains a Book class with two fields: name (CharField) and pub_date (DateField).
Represents the data layer of the application

from django.db import models

class Book(models.Model):

name = models.CharField(max_length=50)

pub_date = models.DateField()

Search Creators... Page 4


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

2. views.py (the business logic):

Implements the latest_books() function as the view.


Retrieves the latest 10 books from the database and passes them to the template for
rendering.
Handles user requests and prepares data for display.

from django.shortcuts import render_to_response

from .models import Book

def latest_books(request):

book_list = Book.objects.order_by('-pub_date')[:10]

return render_to_response('latest_books.html', {'book_list': book_list})

3. urls.py (the URL configuration):

Defines URL patterns and maps them to corresponding views.


Specifies that the URL /latest/ should be handled by the latest_books() view.

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^latest/$', views.latest_books),

3. latest_books.html (the template):

HTML template for rendering the latest books.


Uses Django's template language to iterate over the book_list passed from the view and
display book names in a list.

Search Creators... Page 5


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

<html>

<head>

<title>Books</title>

</head>

<body>

<h1>Books</h1>

<ul>

{% for book in book_list %}

<li>{{ book.name }}</li>

{% endfor %}

</ul>

</body>

</html>

This Django program follows the Model-View-Controller (MVC) design pattern:

Model (models.py): Defines the database model.


View (views.py): Handles business logic and prepares data for display.
Controller (urls.py): Routes URLs to corresponding views.
Template (latest_books.html): Defines the presentation layer and renders data to the user.

The components are loosely coupled, allowing for independent changes and enhancing
maintainability and scalability of the application.

Search Creators... Page 6


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Django Evolution

1. Origins: Django was created by Adrian Holovaty and Simon Willison in the fall of 2003.
They were web programmers at the Lawrence Journal-World newspaper in Lawrence,
Kansas, USA.

2. Development Environment: The team worked in a fast-paced environment with tight


journalism deadlines. They needed to build and maintain web applications quickly and
efficiently.

3. Organic Growth: Django grew organically from the real-world needs of the development
team. They initially built applications from scratch but soon realized the need for a
framework to streamline their process.

4. Framework Creation: Following the typical path of many web developers, the team
started refactoring their code to share common functionalities across applications. This led
to the creation of a framework.

5. Open-Source Release: In the summer of 2005, after developing the framework to a usable
state, the team, including Jacob Kaplan-Moss, decided to release it as open source software
in July 2005.

6. Name Origin: The framework was named Django after the jazz guitarist Django
Reinhardt.

7. Current Status: Today, Django is a well-established open-source project with a large


community of users and contributors worldwide. Adrian Holovaty and Jacob Kaplan-Moss,
two of the original developers, still provide guidance for its growth, but it's now a
collaborative effort.

Search Creators... Page 7


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

8. Sweet Spot: Django's origins in a news environment influenced its design, making it
particularly well-suited for content sites with dynamic, database-driven information.
However, it's effective for building a wide range of dynamic websites.

Version Date Description

0.90 16 Nov 2005

0.91 11 Jan 2006 magic removal

0.96 23 Mar 2007 newforms, testing tools

1.0 3 Sep 2008 API stability, decoupled admin, unicode

1.1 29 Jul 2009 Aggregates, transaction based tests

1.2 17 May 2010 Multiple db connections, CSRF, model validation

1.3 23 Mar 2011 Timezones, in browser testing, app templates.

1.5 26 Feb 2013 Python 3 Support, configurable user model

1.6 6 Nov 2013 Dedicated to Malcolm Tredinnick, db transaction management,


connection pooling.

1.7 2 Sep 2014 Migrations, application loading and configuration.

1.8 LTS 2 Sep 2014 Migrations, application loading and configuration.

1.8 LTS 1 Apr 2015 Native support for multiple template engines.Supported until
at least April 2018

1.9 1 Dec 2015 Automatic password validation. New styling for admin
interface.

1.10 1 Aug 2016 Full text search for PostgreSQL. New-style middleware.

1.11 LTS 1.11 LTS Last version to support Python 2.7.Supported until at least April
2020

Search Creators... Page 8


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

2.0 Dec 2017 First Python 3-only release, Simplified URL routing syntax,
Mobile friendly admin.

Views, Mapping URL to Views

View Creation (views.py):

In Django, views are Python functions that handle web requests and return web responses.
The views.py file is a convention for organizing view functions within a Django project.
To create a view, you define a Python function that takes an HttpRequest object as its first
parameter and returns an HttpResponse object.
In the provided example, the hello view function simply returns an HttpResponse object
with the text "Hello world".

# views.py

from django.http import HttpResponse

def hello(request):

return HttpResponse("Hello world")

Explanation:

Import the HttpResponse class from django. http module.


Define a function named hello which will be the view.
The view function takes a request parameter (an instance of HttpRequest), although it
doesn't use it here.
The view returns an HttpResponse object containing the text "Hello world".

URL Configuration (urls.py):

Django uses a URLconf (URL configuration) to map URLs to view functions.


The urls.py file is where you define the URL patterns for your Django project.

Search Creators... Page 9


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

In the URLconf, you import the view functions from views.py and map them to specific
URLs using regular expressions.
Each URL pattern is defined as a tuple containing a regular expression pattern and the
corresponding view function.
In the provided example, the URL pattern r'^hello/$' maps to the hello view function,
indicating that the view should be invoked when the URL /hello/ is requested.

# urls.py

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^hello/$', views.hello),

Explanation:

Import necessary modules and the hello view function from views.py.
Define the urlpatterns variable, which is a mapping between URLs and the view functions.
Map the URL /hello/ to the hello view function. When a user visits this URL, Django will
call the hello function.

This setup tells Django to display "Hello world" when a user navigates to the /hello/ URL in the
browser.

Request Handling:

When a user makes a request to the Django server, Django's URL resolver examines the
requested URL and determines which view function to call based on the URLconf.
The view function receives an HttpRequest object as its first parameter, which contains
metadata about the request (e.g., headers, user agent, request method).
Although the hello view function doesn't utilize the HttpRequest object in this example, it's
a standard parameter for all view functions in Django.

Search Creators... Page 10


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Response Generation:

View functions in Django are responsible for generating web responses.


In the provided example, the hello view function returns an HttpResponse object containing
the string "Hello world".
Django's HttpResponse class allows you to create HTTP responses with custom content
(e.g., HTML, JSON) and status codes.

URL Mapping:

URL patterns defined in the URLconf serve as a mapping between URLs and view
functions.
Django uses regular expressions to match incoming URLs to patterns defined in the
URLconf.
When a matching URL is found, Django calls the corresponding view function to handle
the request and generate the response.

Working of Django URL Confs and Loose Coupling

In a dynamic web application, URLs often contain parameters that influence the output of the page.
To demonstrate this, let's create a view in Django that displays the current date and time offset by
a certain number of hours. Instead of creating separate views for each hour offset, which would
clutter the URLconf, we can use a single view with a parameter in the URL to specify the hour
offset dynamically.

Search Creators... Page 11


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

View Function:

We'll create a single view function named offset_datetime, which takes an hour offset as a
parameter and returns the current date and time offset by that number of hours.

# views.py

from django.http import HttpResponse

from datetime import datetime, timedelta

def offset_datetime(request, offset):

try:

offset_hours = int(offset)

dt = datetime.now() + timedelta(hours=offset_hours)

return HttpResponse(f"Current date/time offset by {offset_hours} hours: {dt}")

except ValueError:

return HttpResponse("Invalid offset")

2. URL Configuration:

We'll define a dynamic URL pattern with a parameter to specify the hour offset.

# urls.py

from django.conf.urls.defaults import *

from . import views

urlpatterns = patterns('',

(r'^time/plus/(?P<offset>\d+)/$', views.offset_datetime),

Search Creators... Page 12


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Explanation:

The URL pattern r'^time/plus/(?P<offset>\d+)/$' matches URLs like /time/plus/1/,


/time/plus/2/, etc., where the offset parameter specifies the number of hours to add to the
current date/time.
The (?P<offset>\d+) part of the pattern captures the value of the offset parameter as a string
of digits and passes it to the offset_datetime view function.

Loose coupling is a fundamental principle in software development, and Django's URLconfs


provide a clear example of its application within the framework. Here's a breakdown of how
URLconfs and views demonstrate loose coupling in Django:

Definition Separation:

In Django, URLconfs are used to map URLs to view functions, specifying which view
function should be called for a given URL pattern.
The URL definitions and the implementation of view functions are kept separate, residing
in two distinct places within the Django project.

Interchangeability:

Loose coupling ensures that changes made to one component have minimal impact on
others.
If two pieces of code are loosely coupled, modifications to one piece won't require changes
to the other, promoting flexibility and maintainability.

Flexibility in Changes:

With Django's URLconfs, you can modify URL patterns without affecting the view
functions they map to, and vice versa.
For example, changing the URL pattern for a view (e.g., moving from /time/ to /current-
time/) can be accomplished without altering the view function itself.
Similarly, modifications to the view function's logic can be made independently of URL
changes.

Search Creators... Page 13


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Scalability:

Loose coupling enables easy scaling and extension of functionality within a Django project.
Adding new URLs or modifying existing ones can be done without disrupting other parts
of the application.
For instance, exposing a view function at multiple URLs can be achieved by editing the
URLconf without touching the view code.

Maintainability:

Separating URL definitions and view implementations promotes code clarity and makes it
easier to understand and maintain the project.
Developers can focus on specific tasks (e.g., URL routing or view logic) without needing
extensive knowledge of other components.

By leveraging loose coupling, Django enables developers to build web applications that are
flexible, modular, and easy to maintain.

This approach aligns with Django's philosophy of promoting rapid development and scalability
while ensuring code robustness and maintainability.

Errors in Django

When you deliberately introduce a Python error into your Django project, such as commenting out
critical lines of code, Django's error handling mechanisms come into play. Let's delve into how
Django's error pages help you debug and understand the issue:

Error Introduction:

By commenting out crucial lines of code in a view function, you intentionally introduce a
Python error into your Django project.

Search Creators... Page 14


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Error Page Display:

When you navigate to a URL that triggers the error, Django displays a detailed error page
with significant information about the exception.
At the top of the error page, Django presents key information about the exception,
including the type of exception, parameters, file name, and line number where the
exception occurred.
Additionally, Django provides the full Python traceback for the exception, displaying each
level of the stack trace along with the corresponding file, function/method name, and line
number.

Interactive Traceback:

Django's error page offers an interactive traceback, allowing you to click on any line of
source code to view several lines before and after the erroneous line, providing context for
better understanding.
You can also click on "Local vars" under any frame in the stack to view a table of all local
variables and their values at the exact point where the exception was raised, aiding in
debugging.

Sharing and Debugging:

Django offers options to easily share the traceback with others for technical support. You
can switch to a copy-and-paste view or share the traceback on a public website like
http://www.dpaste.com/.
Additionally, the error page includes information about the incoming web request (GET
and POST data, cookies, CGI headers) and Django settings, helping you identify the
context of the error.

Debugging Aid:

Developers accustomed to debugging with print statements can leverage Django's error
page for debugging purposes by inserting an assert False statement at any point in the view
function to trigger the error page and inspect the local variables and program state.

Search Creators... Page 15


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Security Considerations:

It's essential to recognize that the information displayed on Django's error page is sensitive
and should not be exposed on the public internet. Django only displays the error page when
the project is in debug mode, which is automatically activated during development but
should be deactivated in production to prevent potential security risks.

By utilizing Django's error pages effectively, developers can gain valuable insights into
runtime errors, facilitate debugging, and ensure the robustness of their Django applications.

Wild Card patterns in URLS

Wildcard patterns, also known as catch-all patterns or wildcard segments, are a useful feature in
Django's URL routing system. They allow you to capture any part of a URL and pass it as a
parameter to a view function. Here's how wildcard patterns work in Django's URL configuration:

Basic URL Patterns:

In Django, URL patterns are defined using regular expressions (regex) in the URLconf
module (urls.py).
Typically, URL patterns match specific URLs and route them to corresponding view
functions.

Wildcard Patterns:

Wildcard patterns allow you to capture variable parts of a URL and pass them as parameters
to view functions.
The most common wildcard pattern in Django's URL routing system is the
(?P<parameter_name>pattern) syntax, where parameter_name is the name of the parameter
and pattern is a regex pattern that matches the parameter value.
This syntax captures the matched part of the URL and passes it as an argument to the
associated view function.

Search Creators... Page 16


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Usage Example:

Let's say you want to create a dynamic URL pattern for displaying details of a specific
item. Instead of creating separate URL patterns for each item, you can use a wildcard
pattern to capture the item's identifier from the URL.

Example:

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('item/<int:item_id>/', views.item_detail),

In this example, <int:item_id> is a wildcard pattern that captures an integer value from the
URL and passes it as the item_id parameter to the item_detail view function.

Parameter Naming:

When using wildcard patterns, it's important to give meaningful names to the captured
parameters to improve code readability.
Parameter names are enclosed in angle brackets (< >) and must be valid Python variable
names.

Wildcard Segment:

Django also supports wildcard segments in URL patterns, denoted by an asterisk (*), which
captures the remainder of the URL as a single parameter.
Wildcard segments are useful for creating catch-all patterns to handle dynamic routes.

Search Creators... Page 17


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Usage Example with Wildcard Segment:

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('blog/<slug:category>/', views.blog_category),

path('blog/<slug:category>/<path:remainder>/', views.blog_post),

In this example, <path:remainder> is a wildcard segment that captures the remaining part
of the URL as a single parameter, allowing for dynamic handling of blog posts with
variable URLs.

Wildcard patterns in Django's URL routing system provide flexibility and enable the creation of
dynamic and expressive URL patterns, making it easier to build robust and scalable web
applications

Search Creators... Page 18


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Module-03

Django Admin Interfaces and Model Forms

Activating Admin Interfaces

Update settings.py:

Add to INSTALLED_APPS:

'django.contrib.admin'
Ensure 'django.contrib.auth', 'django.contrib.contenttypes', and 'django.contrib.sessions'
are included. Uncomment if previously commented.

Update MIDDLEWARE_CLASSES:

Ensure the following middlewares are included and uncommented:

'django.middleware.common.CommonMiddleware'
'django.contrib.sessions.middleware.SessionMiddleware'
'django.contrib.auth.middleware.AuthenticationMiddleware'

Sync the database:

Run database synchronization:

Execute python manage.py syncdb to install the necessary database tables for the admin
interface.
If not prompted to create a superuser, run python manage.py createsuperuser to create an
admin account.

Update urls.py:

Include the admin site in URLconf:

Ensure the following import statements are present


from django.contrib import admin
admin.autodiscover()

Search Creators... Page 1


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Add the admin URL pattern
urlpatterns = patterns('',
# ...
(r'^admin/', include(admin.site.urls)),
# ...
)

Access the admin interface:

Run the development server and access the admin site:


Start the server with python manage.py runserver.
Visit http://127.0.0.1:8000/admin/ in your web browser.

Using Admin Interfaces

Logging In:

Visit the admin site and log in with the superuser credentials you created.
manage.py
createsuperuser.

Search Creators... Page 2


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Admin Home Page:

After logging in, you'll see the admin home page listing all data types available for
editing. Initially, it includes only Groups and Users.

Figure: - The Django admin home page

Data Management:

Each data type in the admin site has a change list and an edit form.
Change List: Displays all records of a data type, similar to a SELECT * FROM <table>
SQL query.
Edit Form: Allows you to add, change, or delete individual records.

Search Creators... Page 3


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Managing Users:

Click the Change link in the Users row to load the change-list page for users.
This page shows all users in the database, with options for filtering, sorting, and
searching.
Filtering: Options are on the right.
Sorting: Click a column header.
Search: Use the search box at the top.
Click a username to see the edit form for that user.
Change user attributes such as first/last names and permissions.
To change a user's password, click the Change Password Form link.
Different field types have different input widgets (e.g., calendar controls for date fields,
checkboxes for Boolean fields).

Figure: - The user change-list page

Search Creators... Page 4


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Adding and Deleting Records:

Add Record: Click Add in the appropriate column on the admin home page to access an
empty edit form for creating a new record.
Delete Record: Click the Delete button at the bottom left of an edit form. Confirm the
deletion on the subsequent page, which may list dependent objects to be deleted as well.

Figure: - An Adding Records

Search Creators... Page 5


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Input Validation:

The admin interface validates input automatically. Errors will be displayed if you leave
required fields blank or enter invalid data.

Figure: - An edit form displaying errors

History:

When editing an object, a History link appears in the upper-right corner. This logs every
change made through the admin interface and allows you to review the change history.

Figure: - An object history page

Search Creators... Page 6


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Customizing Admin Interfaces

To customize a label, use the verbose_name attribute in your model field definitions.

Example:

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
Alternatively, you can pass verbose_name as a positional argument:

class Author(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=40)

email = models.EmailField('e-mail', blank=True)

Custom Model Admin Classes

ModelAdmin classes allow customization of how models are displayed and managed in
the admin interface.
Customizing Change Lists
By default, change lists show the result of the model's __str__ or __unicode__ method.
You can specify which fields to display using the list_display attribute.

Search Creators... Page 7


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Example:

To display first_name, last_name, and email for the Author model:

from django.contrib import admin

from mysite.books.models import Author

class AuthorAdmin(admin.ModelAdmin):

list_display = ('first_name', 'last_name', 'email')

admin.site.register(Author, AuthorAdmin)

Adding a Search Bar


Add search_fields to your AuthorAdmin:

class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
search_fields = ('first_name', 'last_name')

Adding Date Filters


Add list_filter to your BookAdmin:

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)

Search Creators... Page 8


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Adding Date Hierarchy
Add date_hierarchy to BookAdmin:

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'

Changing Default Ordering


Use ordering to set the default order of records:

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
ordering = ('-publication_date',)

Customizing Edit Forms

Changing Field Order


Use the fields option to customize the order of fields:

class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher', 'publication_date')

Excluding Fields
Exclude fields by omitting them from the fields list:

class BookAdmin(admin.ModelAdmin):
fields = ('title', 'authors', 'publisher')

Search Creators... Page 9


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Many-to-Many Field Widgets
Use filter_horizontal for ManyToManyFields:

class BookAdmin(admin.ModelAdmin):
filter_horizontal = ('authors',)

Alternatively, use filter_vertical:

class BookAdmin(admin.ModelAdmin):
filter_vertical = ('authors',)

ForeignKey Field Widgets


Use raw_id_fields for ForeignKey fields:

class BookAdmin(admin.ModelAdmin):
raw_id_fields = ('publisher',)

Search Creators... Page 10


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Reasons to use Admin Interfaces.

When and Why to Use the Admin Interface and When Not To

When to Use the Admin Interface

1. For Non-Technical Users:


Data Entry: The admin interface is designed to enable non-technical users to easily
enter and manage data. For instance, reporters or content creators can input data
without needing to know any code.

Example Workflow:
1. A reporter meets with a developer to describe the data.
2. The developer creates Django models based on this data and sets up the
admin interface.
3. The reporter reviews the admin site and suggests any changes to the fields.
4. The developer updates the models accordingly.
5. The reporter begins entering data, allowing the developer to focus on
building views and templates.

2. Inspecting Data Models:


Model Validation: The admin interface is useful for developers to enter dummy
data and validate their data models. This process can help identify modeling errors
or inconsistencies early in development.

3. Managing Acquired Data:


External Data Sources: If your application relies on data from external sources
(such as user inputs or web crawlers), the admin interface provides an easy way to
inspect and edit this data. It acts as a convenient tool for data management,
complementing your database's command-line utility.

Search Creators... Page 11


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
4. Quick and Dirty Data-Management Apps:
Lightweight Applications:
a polished public interface, the admin site can serve as a quick solution. For
example, it can be used to track expenses or manage simple data sets, much like a
relational spreadsheet.

When Not to Use the Admin Interface

1. Public Interfaces:
Security and Usability: The admin interface is not designed for public use. It lacks
the security measures and user-friendly design necessary for a public-facing
application.

2. Sophisticated Sorting and Searching:


Advanced Data Handling: While the admin site provides basic sorting and

data queries and manipulations, custom views and tools are more appropriate.

3. Complex User Interfaces:


Customization Limits: The admin interface has limitations in terms of
customization and interactivity. If your project requires a highly customized user
interface with complex workflows, a custom-built solution will be more suitable.

Search Creators... Page 12


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Form Processing

1. Introduction to Forms
Django provides a built-in form handling functionality that simplifies the process
of handling HTML forms in web applications.
Forms in Django are represented by Python classes that map to HTML form fields.

2. Creating a Form
In Django, forms are created by subclassing the forms.Form class or the
forms.ModelForm class (for model-based forms).
Each form field is represented by a class attribute, and the type of the field is
determined by the corresponding Django Field class.

Example:

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

3. Rendering a Form
Forms can be rendered in templates using the {{ form.as_p }} (for paragraph-based
rendering) or {{ form.as_table }} (for table-based rendering) template tags.
Individual form fields can be rendered using {{ form.field_name }}.

Search Creators... Page 13


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
4. Handling Form Data
In the view function, you can access the submitted form data using the
request.POST or request.GET dictionaries.
To bind the form data to the form instance, use form = MyForm(request.POST) or
form = MyForm(request.GET).
After binding the data, you can check if the form is valid using form.is_valid().

5. Validating Form Data


Django provides built-in validation for common field types (e.g., EmailField,
IntegerField, etc.).
You can define custom validation rules by overriding the clean_fieldname() method
in your form class.
For complex validation rules, you can override the clean() method in your form
class.

6. Saving Form Data


For forms not based on models, you can access the cleaned data using
form.cleaned_data and handle it as needed.
For model-based forms (ModelForm), you can create or update model instances
using form.save().

7. Form Widgets
Django provides a wide range of built-in form widgets (e.g., TextInput, Textarea,
CheckboxInput, Select, etc.) for rendering form fields.
You can customize the rendering of form fields by specifying the widget argument
when defining the field.

Search Creators... Page 14


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
8. Form Handling in Views
In the view function, you typically create a form instance, bind the data to it, and
perform validation and data handling.
After successful form submission, you can redirect the user to another page or
render a success message.

9. CSRF Protection
Django provides built-in protection against Cross-Site Request Forgery (CSRF)
attacks by including a CSRF token in forms.
You need to include the {% csrf_token %} template tag in your form template to
generate the CSRF token.

10. Form Inheritance


Django supports form inheritance, allowing you to create reusable form
components and extend or override them as needed.
You can use the Meta class to specify form-level attributes, such as labels,
help_texts, and error_messages.

Search Creators... Page 15


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Creating Feedback forms

Step 1: Create the Feedback Form

Create a new file forms.py in your Django app directory, and add the following code

from django import forms

class FeedbackForm(forms.Form):

name = forms.CharField(max_length=100, label='Your Name')

email = forms.EmailField(label='Your Email')

subject = forms.CharField(max_length=200, label='Subject')

message = forms.CharField(widget=forms.Textarea, label='Your Feedback')

Step 2: Create the Feedback Template

Create a new file feedback.html in your Django app's templates directory, and add the following
code:

<!DOCTYPE html>

<html>

<head>

<title>Feedback Form</title>

</head>

<body>

<h1>Feedback Form</h1>

<form method="post">

Search Creators... Page 16


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
{% csrf_token %}

{{ form.non_field_errors }}

<div>

{{ form.name.errors }}

{{ form.name.label_tag }}

{{ form.name }}

</div>

<div>

{{ form.email.errors }}

{{ form.email.label_tag }}

{{ form.email }}

</div>

<div>

{{ form.subject.errors }}

{{ form.subject.label_tag }}

{{ form.subject }}

</div>

<div>

{{ form.message.errors }}

{{ form.message.label_tag }}

{{ form.message }}

Search Creators... Page 17


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
</div>

<input type="submit" value="Submit Feedback">

</form>

</body>

</html>

Step 3: Create the Success Template

Create a new file feedback_success.html in your Django app's templates directory, and add the
following code:

<!DOCTYPE html>

<html>

<head>

<title>Feedback Submitted</title>

</head>

<body>

<h1>Thank you for your feedback!</h1>

<p>We appreciate your comments and will review them shortly.</p>

</body>

</html>

Search Creators... Page 18


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Step 4: Create the View Function

Open your Django app's views.py file and add the following code:

from django.shortcuts import render

from .forms import FeedbackForm

def feedback(request):

if request.method == 'POST':

form = FeedbackForm(request.POST)

if form.is_valid():

# Process the feedback data

name = form.cleaned_data['name']

email = form.cleaned_data['email']

subject = form.cleaned_data['subject']

message = form.cleaned_data['message']

return render(request, 'feedback_success.html')

else:

form = FeedbackForm()

return render(request, 'feedback.html', {'form': form})

Search Creators... Page 19


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Step 5: Add URL Pattern

Open your Django app's urls.py file and add the following URL pattern:

from django.urls import path

from . import views

urlpatterns = [

# ... other URL patterns

path('feedback/', views.feedback, name='feedback'),

Step 6: Run the Development Server

Start the Django development server and navigate to http://localhost:8000/feedback/ in your web
browser. You should see the feedback form.

Search Creators... Page 20


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Form submissions

1. Create a Form Class: Define a form class that inherits from forms.Form or
forms.ModelForm. This class defines the fields and validations for your form.

2. Render the Form in a Template: In your template, render the form using the {{ form }}
template tag or individual field tags like {{ form.field_name }}.

3. Check Request Method: In your view function, check if the request method is POST
(form submission) or GET (initial form load).

4. Create Form Instance with Data: If the request method is POST, create a form instance
with the submitted data using form = YourForm(request.POST) or form =
YourModelForm(request.POST).

5. Validate the Form: Call form.is_valid() to validate the form data against the defined fields
and validations.

6. Process Valid Form Data: If the form is valid (form.is_valid() returns True), access the
cleaned data using form.cleaned_data and perform any necessary operations (e.g., save to
the database, send an email, etc.).

Search Creators... Page 21


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
7. Handle Invalid Form Data: If the form is invalid (form.is_valid() returns False), re-render
the form with error messages by passing the form instance to the template context.

8. Redirect or Render Success Page: After successful form processing, it's recommended
to redirect the user to a success page or a different view to prevent duplicate form
submissions on page refresh.

# forms.py

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

# views.py

from django.shortcuts import render, redirect

from .forms import ContactForm

def contact(request):

if request.method == 'POST':

form = ContactForm(request.POST)

if form.is_valid():

Search Creators... Page 22


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
# Process the form data

name = form.cleaned_data['name']

email = form.cleaned_data['email']

message = form.cleaned_data['message']

return redirect('success_url')

else:

form = ContactForm()

return render(request, 'contact.html', {'form': form})

<!-- contact.html -->

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Submit">

</form>

Search Creators... Page 23


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Custom Validation

1. Define the Form Class:


Use Django's forms.Form to define the fields of the form

from django import forms

class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)

2. Add a Custom Validation Method:


Create a clean_message() method to enforce the minimum word count.

def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message

This method:
Extracts the message from self.cleaned_data.
Counts the words using split() and len().
Raises a ValidationError if there are fewer than four words.
Returns the cleaned message value.

Search Creators... Page 24


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Customizing Form Design

You can customize the form's appearance using CSS and custom HTML templates
for better control over the presentation.

1. CSS for Error Styling:


Define CSS to style error messages for better visibility
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;
}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;
}
</style>

2. Custom HTML Template:


Instead of using {{ form.as_table }}, manually render the form fields for finer
control.

<html>

<head>

<title>Contact us</title>

</head>

Search Creators... Page 25


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
<body>

<h1>Contact us</h1>

{% if form.errors %}

<p style="color: red;">

Please correct the error{{ form.errors|pluralize }} below.

</p>

{% endif %}

<form action="" method="post">

<div class="field">

{{ form.subject.errors }}

<label for="id_subject">Subject:</label>

{{ form.subject }}

</div>

<div class="field">

{{ form.email.errors }}

<label for="id_email">Your e-mail address:</label>

{{ form.email }}

</div>

<div class="field">

{{ form.message.errors }}

<label for="id_message">Message:</label>

Search Creators... Page 26


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
{{ form.message }}

</div>

<input type="submit" value="Submit">

</form>

</body>

</html>

3. Advanced Error Handling in Template:


Conditionally add classes and display error messages

<div class="field{% if form.message.errors %} errors{% endif %}">


{% if form.message.errors %}
<ul>
{% for error in form.message.errors %}
<li><strong>{{ error }}</strong></li>
{% endfor %}
</ul>
{% endif %}
<label for="id_message">Message:</label>
{{ form.message }}
</div>

This template:

Checks for errors and displays them if present.


Adds an errors class to the <div> if there are validation errors.
Lists individual error messages in an unordered list.

Search Creators... Page 27


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Creating Model Forms

1. Define the Model


Objective: Create a Django model to represent the data structure.

Example

from django.db import models

class Contact(models.Model):

subject = models.CharField(max_length=100)

email = models.EmailField(blank=True)

message = models.TextField()

def __str__(self):

return self.subject

2. Create the Model Form


Objective: Use forms.ModelForm to create a form based on the model.

Example

from django import forms

from .models import Contact

class ContactForm(forms.ModelForm):

class Meta:

model = Contact

fields = ['subject', 'email', 'message']

Search Creators... Page 28


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
3. Add Custom Validation (Optional)
Objective: Add custom validation logic specific to form fields.

Example:

class ContactForm(forms.ModelForm):

class Meta:

model = Contact

fields = ['subject', 'email', 'message']

def clean_message(self):

message = self.cleaned_data['message']

num_words = len(message.split())

if num_words < 4:

raise forms.ValidationError("Not enough words!")

return message

4. Use the Form in Views


Objective: Handle the form submission and validation within Django views.

Example

from django.shortcuts import render, redirect

from .forms import ContactForm

def contact_view(request):

Search Creators... Page 29


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
if request.method == 'POST':

form = ContactForm(request.POST)

if form.is_valid():

form.save()

return redirect('success') # Redirect to a success page or another view

else:

form = ContactForm()

return render(request, 'contact_form.html', {'form': form})

5. Create the Template


Objective: Design an HTML template to render and display the form.

Example

<html>

<head>

<title>Contact Us</title>

</head>

<body>

<h1>Contact Us</h1>

{% if form.errors %}

<p style="color: red;">

Please correct the error{{ form.errors|pluralize }} below.

Search Creators... Page 30


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
</p>

{% endif %}

<form method="post">

{% csrf_token %}

<div class="field">

{{ form.subject.errors }}

<label for="id_subject">Subject:</label>

{{ form.subject }}

</div>

<div class="field">

{{ form.email.errors }}

<label for="id_email">Your email address:</label>

{{ form.email }}

</div>

<div class="field">

{{ form.message.errors }}

<label for="id_message">Message:</label>

{{ form.message }}

</div>

<input type="submit" value="Submit">

</form>

Search Creators... Page 31


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
</body>

</html>

1. Define the Model: Establish your data structure with a Django model.
2. Create the Model Form: Generate a form using forms.ModelForm based on the model.
3. Add Custom Validation: Optionally include custom validation methods within the form.
4. Use the Form in Views: Implement form handling logic in Django views to process
submissions.
5. Create the Template: Design an HTML template to display and manage the form
interface.

URLConf Ticks

Streamlining Function Imports

1. Traditional Method: Direct Import of View Functions

Example:

from django.conf.urls.defaults import *


from mysite.views import hello, current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)
Disadvantage: Tedious to manage imports as the application grows.

Search Creators... Page 32


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
2. Importing the Views Module

Example
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
(r'^hello/$', views.hello),
(r'^time/$', views.current_datetime),
(r'^time/plus/(d{1,2})/$', views.hours_ahead),
)

Advantage: Simplifies imports, but still requires module import.

3. Using Strings to Specify View Functions

Example
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^hello/$', 'mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(d{1,2})/$', 'mysite.views.hours_ahead'),
)
Advantage: No need to import view functions; Django handles imports
automatically.

Search Creators... Page 33


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
4. Factoring Out a Common View Prefix

Example:

from django.conf.urls.defaults import *

urlpatterns = patterns('mysite.views',

(r'^hello/$', 'hello'),

(r'^time/$', 'current_datetime'),

(r'^time/plus/(d{1,2})/$', 'hours_ahead'),

Advantage: Reduces redundancy by factoring out common prefixes.

Choosing Between Methods

Advantages of the String Approach:


More compact, no need to import view functions explicitly.
More readable and manageable for projects with views in multiple modules.

Advantages of the Function Object Approach:


Facilitates easy wrapping of view functions.
More "Pythonic," aligning with Python traditions of passing functions as objects.

Flexibility:
Both approaches are valid and can be mixed within the same URLconf depending
on personal coding style and project needs.

Search Creators... Page 34


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Including Other URLConfs

Purpose and Benefit

1. Purpose: Allows for modular organization of URL patterns by "including" URLconf


modules from different parts of the project.
2. Benefit: Enhances reusability and maintainability across multiple Django-based sites.

Basic Usage

Example URLconf that includes other URLconfs.

from django.conf.urls.defaults import *


urlpatterns = patterns('',
(r'^weblog/', include('mysite.blog.urls')),
(r'^photos/', include('mysite.photos.urls')),
(r'^about/$', 'mysite.views.about'),
)

Important Considerations

1. No End-of-String Match Character: Regular expressions pointing to an include() should


not have a $ but should include a trailing slash.
2. URL Stripping: When Django encounters include(), it removes the matched part of the
URL and sends the remaining string to the included URLconf.

Search Creators... Page 35


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Example Breakdown

Main URLconf:

from django.conf.urls.defaults import *

urlpatterns = patterns('',

(r'^weblog/', include('mysite.blog.urls')),

(r'^photos/', include('mysite.photos.urls')),

(r'^about/$', 'mysite.views.about'),

Included URLconf (mysite.blog.urls):


from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^(\d\d\d\d)/$', 'mysite.blog.views.year_detail'),
(r'^(\d\d\d\d)/(\d\d)/$', 'mysite.blog.views.month_detail'),
)

Sample Request Handling

1. Request: /weblog/2007/
First URLconf: r'^weblog/' matches.
Action: Strips weblog/.
Remaining URL: 2007/.
Result: Matches r'^(\d\d\d\d)/$' in mysite.blog.urls.

Search Creators... Page 36


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
2. Request: /weblog//2007/ (with two slashes)
First URLconf: r'^weblog/' matches.
Action: Strips weblog/.
Remaining URL: /2007/ (with leading slash).
Result: Does not match any patterns in mysite.blog.urls.

3. Request: /about/
First URLconf: Matches r'^about/$'.
Result: Maps to mysite.views.about view.

Mixing Patterns

Flexibility: You can mix include() patterns with non-include() patterns within the same
URLconf.

Search Creators... Page 37


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Module-04

Generic Views and Django State Persistence

Using Generic Views

Basic Concept

Generic Views: Django provides built-in views that can handle common patterns,
reducing the need to write repetitive view code.
Configuration: Use configuration dictionaries in URLconf files, passing them as the third
member of the URLconf tuple.

Example: Static "About" Page

1. Simple URLconf

from django.conf.urls.defaults import *


from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
(r'^about/$', direct_to_template, {'template': 'about.html'})
)
Explanation: direct_to_template is used to render about.html without additional view
code.

Search Creators... Page 1


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Advanced Example: Dynamic Static Pages

Goal: Render about/<whatever>.html for URLs of the form /about/<whatever>/.

1. Modify URLconf to Point to a View Function:

from django.conf.urls.defaults import *


from django.views.generic.simple import direct_to_template
from mysite.books.views import about_pages

urlpatterns = patterns('',
(r'^about/$', direct_to_template, {'template': 'about.html'}),
(r'^about/(\w+)/$', about_pages),
)

2. Write the View Function:

from django.http import Http404


from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template

def about_pages(request, page):


try:
return direct_to_template(request, template="about/%s.html" % page)
except TemplateDoesNotExist:
raise Http404()

Explanation:

Function: about_pages dynamically constructs the template path.


Error Handling: Catches TemplateDoesNotExist exceptions and raises Http404 to prevent
server errors for missing templates.

Search Creators... Page 2


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
1. Generic Views:

Used by creating configuration dictionaries in URLconf.


Examples include direct_to_template for rendering static templates.
Other generic views include list views, detail views, and more.

2. Advantages:

Reduces boilerplate code.


Increases readability and maintainability.
Can be reused within custom view functions.

3. Custom View Integration:

Generic views can be called within custom views, returning HttpResponse objects
directly.
Custom error handling, like catching TemplateDoesNotExist, can be implemented for
more robust applications.

Search Creators... Page 3


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Generic Views of Objects

Purpose: Simplifies creating views that display lists and details of database objects.
Benefits: Reduces repetitive code, leverages built-in Django functionality for common
tasks.

Example: Object List View

1. Model Definition:
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

def __unicode__(self):
return self.name

class Meta:
ordering = ['name']

2. Basic URLconf for Object List View:


from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher
publisher_info = {
'queryset': Publisher.objects.all(),
}
urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)

Search Creators... Page 4


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
3. Specifying a Template:
You can explicitly specify the template to be used.

from django.conf.urls.defaults import *


from django.views.generic import list_detail
from mysite.books.models import Publisher

publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
}

urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)

Default Template: If template_name is not specified, Django infers the template


name based on the model and app name, e.g., books/publisher_list.html.

4. Template Example:
{% extends "base.html" %}

{% block content %}
<h2>Publishers</h2>
<ul>
{% for publisher in object_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
{% endblock %}
Context Variable: object_list contains all publisher objects.

Search Creators... Page 5


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Customizing Generic Views

Info Dictionary: The dictionary passed to the generic view can be customized to
include additional options.
Template Context: Additional context variables can be passed to the template by
modifying the dictionary.
Generic View Options: Appendix C of the Django documentation provides
detailed information on all available options for generic views.

1. Ease of Use: Generic views simplify the creation of common views for database objects.
2. Flexibility: Options in the info dictionary allow for extensive customization without
writing additional view code.
3. Template Inference: Django can infer template names, but explicit specification is
possible for better control.
4. Reusability: Generic views promote code reusability and maintainability across projects.

Extending Generic Views of objects

Using generic views can significantly speed up development in Django, but there are
times when they need to be extended to handle more complex use cases.
Here are some common patterns for extending generic views:

Making "Friendly" Template Contexts

Instead of using the default variable name object_list, use a more descriptive name like
publisher_list. This can be achieved with the template_object_name argument.

Search Creators... Page 6


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Example:

from django.conf.urls.defaults import *

from django.views.generic import list_detail

from mysite.books.models import Publisher

publisher_info = {

'queryset': Publisher.objects.all(),

'template_name': 'publisher_list_page.html',

'template_object_name': 'publisher',

urlpatterns = patterns('',

(r'^publishers/$', list_detail.object_list, publisher_info)

Search Creators... Page 7


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Template:

{% extends "base.html" %}

{% block content %}

<h2>Publishers</h2>

<ul>

{% for publisher in publisher_list %}

<li>{{ publisher.name }}</li>

{% endfor %}

</ul>

{% endblock %}.

Adding Extra Context

You can add extra context to the template by using the extra_context argument. Use a
callable to ensure the context is evaluated each time the view is called.

publisher_info = {
'queryset': Publisher.objects.all(),
'template_object_name': 'publisher',
'extra_context': {'book_list': Book.objects.all}
}

Search Creators... Page 8


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Viewing Subsets of Objects

Customize the queryset to filter objects.

Example

apress_books = {

'queryset': Book.objects.filter(publisher__name='Apress Publishing'),

'template_name': 'books/apress_list.html'

urlpatterns = patterns('',

(r'^publishers/$', list_detail.object_list, publisher_info),

(r'^books/apress/$', list_detail.object_list, apress_books),

Search Creators... Page 9


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Complex Filtering with Wrapper Functions

Use a wrapper function to filter objects based on URL parameters.

Example

from django.shortcuts import get_object_or_404

from django.views.generic import list_detail

from mysite.books.models import Book, Publisher

def books_by_publisher(request, name):

publisher = get_object_or_404(Publisher, name__iexact=name)

return list_detail.object_list(

request,

queryset=Book.objects.filter(publisher=publisher),

template_name='books/books_by_publisher.html',

template_object_name='book',

extra_context={'publisher': publisher}

urlpatterns = patterns('',

(r'^publishers/$', list_detail.object_list, publisher_info),

(r'^books/(\w+)/$', books_by_publisher),

Search Creators... Page 10


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Performing Extra Work

Perform additional operations before or after calling the generic view.

Example: Updating Last Accessed Field

import datetime

from django.shortcuts import get_object_or_404

from django.views.generic import list_detail

from mysite.books.models import Author

def author_detail(request, author_id):

response = list_detail.object_detail(

request,

queryset=Author.objects.all(),

object_id=author_id,

now = datetime.datetime.now()

Author.objects.filter(id=author_id).update(last_accessed=now)

return response

urlpatterns = patterns('',

# ...

(r'^authors/(?P<author_id>\d+)/$', author_detail),

# ...

Search Creators... Page 11


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Example: Downloadable Plain-Text Version.

def author_list_plaintext(request):

response = list_detail.object_list(

request,

queryset=Author.objects.all(),

mimetype='text/plain',

template_name='books/author_list.txt'

response["Content-Disposition"] = "attachment; filename=authors.txt"

return response

Search Creators... Page 12


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
MIME Types

1. Structure:
MIME types have a format: type/subtype.
Example: image/jpeg for JPEG images.

2. Common MIME Types:

Text

Plain Text: text/plain


Example: A .txt file containing simple text.

HTML: text/html
Example: An .html file for web pages.

CSS: text/css
Example: A .css file for styling web pages.
Image
JPEG: image/jpeg
Example: A .jpg or .jpeg file.
PNG: image/png
Example: A .png file.
GIF: image/gif
Example: A .gif file for simple animations.
Audio
MP3: audio/mpeg
Example: An .mp3 music file.
WAV: audio/wav
Example: A .wav sound file.

Search Creators... Page 13


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Video
MP4: video/mp4
Example: An .mp4 video file.
WebM: video/webm
Example: A .webm video file.

Application
JSON: application/json
Example: A .json file for structured data.
PDF: application/pdf
Example: A .pdf document.
ZIP: application/zip
Example: A .zip compressed file.
Word Document: application/vnd.openxmlformats-
officedocument.wordprocessingml.document
Example: A .docx file created by Microsoft Word.

3. Usage in HTTP:
MIME types are specified in HTTP headers to indicate the type of content.

Example

HTTP/1.1 200 OK

Content-Type: text/html; charset=UTF-8

This header tells the client that the content is an HTML document.

Search Creators... Page 14


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
4. Usage in Emails:
MIME types are used to specify the format of email content and attachments.
Example: An email with a plain text body and an image attachment might have:
Content-Type: text/plain
Content-Type: image/jpeg for the attached image.

5. Custom MIME Types:


Custom or non-standard types often start with x-.
Example: application/x-custom-type

6. Registration:
Official MIME types are registered with IANA (Internet Assigned Numbers
Authority).

Search Creators... Page 15


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Generating Non-HTML contents like CSV and PDF

1. CSV Format:
Simple data format for table rows, separated by commas.
Example
Year, Unruly Airline Passengers
1995,146
1996,184
1997,235
1998,200
1999,226
2000,251
2001,299
2002,273
2003,281
2004,304
2005,203
2006,134
2007,147

Search Creators... Page 16


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
2. Using Python's CSV Library:
Python's csv module handles CSV file operations.
Example of generating CSV with Django:
import csv
from django.http import HttpResponse

UNRULY_PASSENGERS = [146, 184, 235, 200, 226, 251, 299, 273, 281, 304,
203, 134, 147]

def unruly_passengers_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="unruly.csv"'
writer = csv.writer(response)
writer.writerow(['Year', 'Unruly Airline Passengers'])
for year, num in zip(range(1995, 2008), UNRULY_PASSENGERS):
writer.writerow([year, num])
return response

MIME Type: Set Content-Type to text/csv to indicate CSV format.


Content-Disposition: Include attachment; filename="unruly.csv" to prompt file
download.
HttpResponse as File: Use HttpResponse object with csv.writer.
Writing Rows: Use writer.writerow() to write each row in the CSV file.

Search Creators... Page 17


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Generating PDFs with Django

1. PDF Format:
PDF (Portable Document Format) is used for printable documents with precise
formatting.

2. Using ReportLab Library:


ReportLab is a library for generating PDFs in Python.
Installation:
Download from ReportLab Downloads.
Verify installation: import reportlab.

3. Example of Generating PDFs:


Use ReportLab to create customized PDF documents dynamically.
Installation: Install ReportLab from the official website.
Import Test: Verify installation by importing ReportLab in Python

Search Creators... Page 18


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Syndication Feed Framework

High-level framework for generating RSS and Atom feeds.


Create multiple feeds using simple Python classes.
Feeds are conventionally accessed via the /feeds/ URL.

1. Initialization:
Add a URLconf to activate syndication feeds.

(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),

This directs all URLs starting with /feeds/ to the RSS framework.
Customize the URL prefix (feeds/) as needed.

2. URL Configuration:
Use feed_dict to map feed slugs to Feed classes:
from django.conf.urls.defaults import *
from mysite.feeds import LatestEntries, LatestEntriesByCategory
feeds = {
'latest': LatestEntries,
'categories': LatestEntriesByCategory,
}
urlpatterns = patterns('',
# ...
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
# ...
)

Example:

feeds/latest/ for the LatestEntries feed.


feeds/categories/ for the LatestEntriesByCategory feed.

Search Creators... Page 19


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
3. Feed Class:
Define Feed classes to represent syndication feeds.
Subclass django.contrib.syndication.feeds.Feed.
Feed classes can be placed anywhere in the code tree.

4. Feed Class Example:


Simple feed (e.g., latest blog entries):
from django.contrib.syndication.views import Feed

class LatestEntries(Feed):
title = "Latest Blog Entries"
link = "/latest/"
description = "Updates on the latest blog entries."

def items(self):
return Entry.objects.order_by('-pub_date')[:5]

def item_title(self, item):


return item.title

def item_description(self, item):


return item.description

Add URLconf for syndication.


Map URLs to Feed classes using feed_dict.
Define Feed classes by subclassing Feed.
Customize and extend feeds based on application needs.

Search Creators... Page 20


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Sitemap Framework

A sitemap is an XML file that helps search engines index your site.
Tells search engines how frequently pages change and their importance.
Example
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.djangoproject.com/documentation/</loc>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>http://www.djangoproject.com/documentation/0_90/</loc>
<changefreq>never</changefreq>
<priority>0.1</priority>
</url>
</urlset>

1. Installation:
Add 'django.contrib.sitemaps' to INSTALLED_APPS.
Ensure 'django.template.loaders.app_directories.load_template_source' is in
TEMPLATE_LOADERS.
Install the sites framework.

2. Initialization:
Add this line to URLconf to activate sitemap generation
(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':
sitemaps})
The dot in sitemap.xml is escaped with a backslash.

Search Creators... Page 21


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
3. URL Configuration:
Define sitemaps dictionary mapping section labels to Sitemap classes
from django.conf.urls.defaults import *
from mysite.blog.models import Entry
from django.contrib.sitemaps import Sitemap

class BlogSitemap(Sitemap):
changefreq = "never"
priority = 0.5

def items(self):
return Entry.objects.filter(is_draft=False)

def lastmod(self, obj):


return obj.pub_date

sitemaps = {
'blog': BlogSitemap,
}

urlpatterns = patterns('',
(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':
sitemaps}),
)

4. Sitemap Class:
Subclass django.contrib.sitemaps.Sitemap.
Define methods and attributes such as items, lastmod, changefreq, priority.

Search Creators... Page 22


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
5. Example Sitemap Class:

from django.contrib.sitemaps import Sitemap

from mysite.blog.models import Entry

class BlogSitemap(Sitemap):

changefreq = "never"

priority = 0.5

def items(self):

return Entry.objects.filter(is_draft=False)

def lastmod(self, obj):

return obj.pub_date

6. Convenience Classes:
FlatPageSitemap: For flatpages defined for the current site.
GenericSitemap: Works with generic views.

Search Creators... Page 23


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
7. Example with GenericSitemap and FlatPageSitemap:
from django.conf.urls.defaults import *
from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
from mysite.blog.models import Entry

info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
sitemaps = {
'flatpages': FlatPageSitemap,
'blog': GenericSitemap(info_dict, priority=0.6),
}
urlpatterns = patterns('',
(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

8. Creating a Sitemap Index:


Use two views in URLconf
(r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
(r'^sitemap-(?P<section>.+).xml$', 'django.contrib.sitemaps.views.sitemap',
{'sitemaps': sitemaps}),

Search Creators... Page 24


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
9. Pinging Google:
Use ping_google function to notify Google of sitemap changes.
Example
from django.contrib.sitemaps import ping_google

class Entry(models.Model):
# ...
def save(self, *args, **kwargs):
super(Entry, self).save(*args, **kwargs)
try:
ping_google()
except Exception:
pass

Command-line:
python manage.py ping_google /sitemap.xml

Search Creators... Page 25


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Cookies, Sessions

Introduction to Cookies:

Cookies help overcome HTTP's statelessness by storing small pieces of


information in the browser.
Browsers send cookies back to the server with each request, allowing servers to
recognize returning users.

How Cookies Work:

Example:
Browser requests a page from Google:
GET / HTTP/1.1
Host: google.com

Google responds with a Set-Cookie header:


HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671;
expires=Sun, 17-Jan-2038 19:14:07 GMT;
path=/; domain=.google.com
Server: GWS/2.1

Browser stores the cookie and sends it back on subsequent requests


GET / HTTP/1.1
Host: google.com
Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671

Search Creators... Page 26


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Getting and Setting Cookies in Django:

Reading Cookies:
Use the COOKIES attribute of HttpRequest to read cookies.
def show_color(request):
if "favorite_color" in request.COOKIES:
return HttpResponse("Your favorite color is %s" %
request.COOKIES["favorite_color"])
else:
return HttpResponse("You don't have a favorite color.")

Writing Cookies:
Use the set_cookie() method of HttpResponse to set cookies.
def set_color(request):
if "favorite_color" in request.GET:
response = HttpResponse("Your favorite color is now %s" %
request.GET["favorite_color"])
response.set_cookie("favorite_color", request.GET["favorite_color"])
return response
else:
return HttpResponse("You didn't give a favorite color.")

Search Creators... Page 27


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Optional Arguments for set_cookie():
You can pass various optional arguments to response.set_cookie() to control
aspects of the cookie, such as:
max_age: The maximum age of the cookie in seconds.
expires: The expiration date of the cookie.
path: The path for which the cookie is valid.
domain: The domain for which the cookie is valid.
secure: If True, the cookie will only be sent over HTTPS.
httponly: If True, the cookie will only be accessible via HTTP(S) and not
via client-side scripts.

Problems with Cookies:


Voluntary Storage:
Clients can choose not to accept or store cookies, making them unreliable.
Developers should verify if a user accepts cookies before relying on them.

Security Concerns:
Cookies sent over HTTP are vulnerable to snooping attacks.
Never store sensitive information in cookies.
Man-in-the-Middle Attacks: Attackers can intercept and use cookies to impersonate
users.
Tampering:
Browsers allow users to edit cookies, making it risky to store important state
information in cookies.
Example of a security mistake:
# Storing something like IsLoggedIn=1 in a cookie can be easily tampered with.

Use secure methods (e.g., HTTPS) to transmit cookies.


Avoid storing sensitive information directly in cookies.
Validate and sanitize all data received from cookies.

Search Creators... Page 28


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.

Django's session framework addresses the limitations and potential security issues of using
cookies directly by providing a way to store and retrieve arbitrary data on a per-site visitor
basis.
The session data is stored server-side, with only a hashed session ID sent to the client,
mitigating many common cookie-related issues.

Enabling Sessions
Middleware and Installed Apps:
Ensure SessionMiddleware is included in your MIDDLEWARE_CLASSES

MIDDLEWARE_CLASSES = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
Ensure django.contrib.sessions is in your INSTALLED_APPS.

INSTALLED_APPS = [
...
'django.contrib.sessions',
...
]

Using Sessions in Views

When SessionMiddleware is enabled, each HttpRequest object has a session attribute,


which behaves like a dictionary:
Setting a session value
request.session["fav_color"] = "blue"

Search Creators... Page 29


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Getting a session value:
fav_color = request.session["fav_color"]

Clearing a session value


del request.session["fav_color"]

Checking if a session key exists


if "fav_color" in request.session:
...
Session Usage Rules
Use normal Python strings for dictionary keys on request.session.
Avoid using keys that start with an underscore, as they are reserved for internal use
by Django.
Do not replace request.session with a new object or set its attributes directly.

1. Example Views
Preventing Multiple Comments:
def post_comment(request):
if request.method != 'POST':
raise Http404('Only POSTs are allowed')
if 'comment' not in request.POST:
raise Http404('Comment not submitted')
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=request.POST['comment'])
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')

Search Creators... Page 30


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
2. Logging In
def login(request):
if request.method != 'POST':
raise Http404('Only POSTs are allowed')
try:
m = Member.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponseRedirect('/you-are-logged-in/')
except Member.DoesNotExist:
return HttpResponse("Your username and password didn't match.")

3. Logging Out:
def logout(request):
try:
del request.session['member_id']
except KeyError:
pass
return HttpResponse("You're logged out.")
Testing Cookie Acceptance
To test if a browser accepts cookies:
Set the test cookie
request.session.set_test_cookie()

Check if the test cookie worked in a subsequent view


if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponse("You're logged in.")
else:
return HttpResponse("Please enable cookies and try again.")

Search Creators... Page 31


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Sessions Outside of Views

from django.contrib.sessions.models import Session

s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')

session_data = s.get_decoded()

Session Saving Behavior

By default, Django saves the session to the database only if it has been modified:

request.session['foo'] = 'bar' # Modified

del request.session['foo'] # Modified

request.session['foo'] = {} # Modified

request.session['foo']['bar'] = 'baz' # Not Modified.

To save the session on every request, set SESSION_SAVE_EVERY_REQUEST to True.

Browser-Length vs. Persistent Sessions

Persistent sessions (default): Cookies are stored for SESSION_COOKIE_AGE seconds


(default: two weeks).
Browser-length sessions: Set SESSION_EXPIRE_AT_BROWSER_CLOSE to True to
use browser-length cookies.

Search Creators... Page 32


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
Session Settings

SESSION_COOKIE_DOMAIN: Domain for session cookies.


SESSION_COOKIE_NAME: Name of the session cookie.
SESSION_COOKIE_SECURE: Use secure cookies (only sent via HTTPS).

Users and Authentication

1. Django Auth/Auth System Overview


Authentication: Verify user identity using username and password.
Authorization: Grant permissions to users to perform specific tasks.

2. Components of the Auth/Auth System


Users: Registered users on the site.
Permissions: Flags indicating user capabilities.
Groups: Labels and permissions for multiple users.
Messages: Queue and display system messages.

Search Creators... Page 33


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
3. Enabling Authentication Support
Ensure the session framework is installed.
Add 'django.contrib.auth' to INSTALLED_APPS and run manage.py syncdb.
Include 'django.contrib.auth.middleware.AuthenticationMiddleware' in
MIDDLEWARE_CLASSES after SessionMiddleware.
# settings.py
INSTALLED_APPS = [
...
'django.contrib.auth',
...
]
MIDDLEWARE_CLASSES = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
]
4. Accessing User Information
Use request.user to access the logged-in user.
Check if a user is authenticated with request.user.is_authenticated()
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.

5. User Object Fields


Fields: username, first_name, last_name, email, password, is_staff, is_active,
is_superuser, last_login, date_joined.

Search Creators... Page 34


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
6. User Object Methods
Methods: is_authenticated(), is_anonymous(), get_full_name(),
set_password(passwd), check_password(passwd), get_group_permissions(),
get_all_permissions(), has_perm(perm), has_perms(perm_list),
has_module_perms(app_label), get_and_delete_messages(), email_user(subj,
msg).
7. Managing User Groups and Permissions
user.groups.add(group1, group2, ...)
user.groups.remove(group1, group2, ...)
user.groups.clear()
user.permissions.add(permission1, permission2, ...)
user.permissions.remove(permission1, permission2, ...)
user.permissions.clear()

8. Logging In and Out


Use auth.authenticate(username, password) to verify credentials.
Use auth.login(request, user) to log in a user.
Use auth.logout(request) to log out a user.
from django.contrib import auth
def login_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user)
return HttpResponseRedirect("/account/loggedin/")
else:
return HttpResponseRedirect("/account/invalid/")
def logout_view(request):
auth.logout(request)
return HttpResponseRedirect("/account/loggedout/")

Search Creators... Page 35


21CS62 | FULLSTACK DEVELOPMENT | SEARCH CREATORS.
9. Built-in View Functions for Login and Logout
Add URL patterns for login and logout views: (r'^accounts/login/$', login),
(r'^accounts/logout/$', logout).
Customize login templates and redirect URLs using hidden fields and GET
parameters.

10. Restricting Access to Logged-in Users


Use request.user.is_authenticated() to check access in views.
Use login_required decorator for views to ensure user authentication.

11. Restricting Access Based on User Permissions


Check permissions directly in views: request.user.has_perm('polls.can_vote').
Use user_passes_test and permission_required decorators to enforce permissions.

12. Managing Users, Permissions, and Groups via Admin Interface


Admin interface provides an easy way to manage users and their permissions.
Low-level APIs available for absolute control over user management.

13. Creating and Managing Users Programmatically


Create users using User.objects.create_user(username, email, password).
Change passwords using user.set_password(new_password).

14. Handling User Registration


Implement custom views for user registration using UserCreationForm.
Example view provided for user registration with form validation and template
rendering.

15. Using Authentication Data in Templates


{{ user }} template variable for accessing the current user.
{{ perms }} template variable for checking user permissions within templates.

Search Creators... Page 36

You might also like