Notes Fullstack Development Divya.docx
Notes Fullstack Development Divya.docx
Notes Fullstack Development Divya.docx
AY: 2023 – 24
EVEN Semester
JI
Prepared by:
Prof. Divya
Asst. Professor, Dept of ISE, AJIET
A
professionals.
ET
M3: To identify the common areas of interest amongst the individuals for the effective industry- institute
partnership in a sustainable way by systematically working together.
M4: To promote the entrepreneurial attitude and inculcate innovative ideas among the engineering
ET
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering
JI
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and Team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
A
ET
Teaching-Learning Process (General Instructions)
These are sample Strategies, which teachers can use to accelerate the attainment of the various course outcomes.
1. Lecturer method (L) need not to be only a traditional lecture method, but alternative effective teaching
methods could be adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes criticalthinking.
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop designthinking
skills such as the ability to design, evaluate, generalize, and analyze information rather than simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem with different logic and encourage thestudents to come
up with their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it
helps improve the students' understanding.
JI
Course Outcomes (Course Skill Set) At the end of the course the student will be able to:
● CO 1. Understand the working of MVT based full stack web development with Django.
● CO 2. Designing of Models and Forms for rapid development of web pages.
● CO 3. Analyze the role of Template Inheritance and Generic views for developing full stack web applications.
● CO 4. Apply the Django framework libraries to render nonHTML contents like CSV and PDF.
● CO 5. Perform jQuery based AJAX integration to Django Apps to build responsive full stack web applications,
A
Web framework, MVC Design Pattern, Django Evolution, Views, Mapping URL to Views, Working of Django URL Confs
and Loose Coupling, Errors in Django, Wild Card patterns in URLS.
Textbook 1: Chapter 1 and Chapter 3
Laboratory Component: 1. Installation of Python, Django and Visual Studio code editors can be demonstrated. 2.
Creation of virtual environment, Django project and App should be demonstrated 3. Develop a Django app that displays
current date and time in server 4. Develop a Django app that displays date and time four hours ahead and four hours before
as an offset of current date and time in server.
Teaching-Learning Process
1. Demonstration using Visual Studio Code
2. PPT/Prezi Presentation for Architecture and Design Patterns
3. Live coding of all concepts with simple examples
Module-2: Django Templates and Models
Template System Basics, Using Django Template System, Basic Template Tags and Filters, MVT Development Pattern,
Template Loading, Template Inheritance, MVT Development Pattern. Configuring Databases, Defining and Implementing
Models, Basic Data Access, Adding Model String Representations, Inserting/Updating data, Selecting and deleting objects,
Schema Evolution
Textbook 1: Chapter 4 and Chapter 5
Laboratory Component: 1. Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event 2. Develop a layout.html with a suitable header (containing navigation menu) and footer with
copyright and developer information. Inherit this layout.html and create 3 additional pages: contact us, About Us and Home
page of any website. 3. Develop a Django app that performs student registration to a course. It should also display list of
students registered for any selected course. Create students and course as models with enrolment as ManyToMany field.
Teaching-Learning Process 1. Demonstration using Visual Studio Code 2. PPT/Prezi Presentation for Architecture and
Design Patterns 3. Live coding of all concepts with simple examples 4. Case Study: Apply concepts learnt for an Online
Ticket Booking System
2.
ET
Textbook 1: Chapters 6, 7 and 8
Laboratory Component:
1.
Module-3: Django Admin Interfaces and Model Forms
Activating Admin Interfaces, Using Admin Interfaces, Customizing Admin Interfaces, Reasons to use Admin Interfaces.
Form Processing, Creating Feedback forms, Form submissions, custom validation, creating Model Forms, URLConf Ticks,
For student and course models created in Lab experiment for Module2, register admin interfaces, perform
migrations and illustrate data entry through admin forms.
Develop a Model form for student that contains his topic chosen for project, languages used and duration with a
model called project.
Teaching-Learning Process 1. Demonstration using Visual Studio Code 2. PPT/Prezi Presentation for Architecture and
Design Patterns 3. Live coding of all concepts with simple examples
Module-4: Generic Views and Django State Persistence
Using Generic Views, Generic Views of Objects, Extending Generic Views of objects, Extending Generic Views. MIME
JI
Types, Generating Non-HTML contents like CSV and PDF, Syndication Feed Framework, Sitemap framework, Cookies,
Sessions, Users and Authentication.
Textbook 1: Chapters 9, 11 and 12
Laboratory Component:
1. For students enrolment developed in Module 2, create a generic class view which displays list of students and
detailview that displays student details for any selected student in the list.
2. Develop example Django app that performs CSV and PDF generation for any models created in previous laboratory
component.
A
Teaching-Learning Process
1. Demonstration using Visual Studio Code
2. PPT/Prezi Presentation for Architecture and Design Patterns
3. Live coding of all concepts with simple examples
4. Project Work: Implement all concepts learnt for Student Admission Management.
Module-5: jQuery and AJAX Integration in Django
Ajax Solution, Java Script, XHTMLHttpRequest and Response, HTML, CSS, JSON, iFrames, Settings of Java Script in
Django, jQuery and Basic AJAX, jQuery AJAX Facilities, Using jQuery UI Autocomplete in Django
Textbook 2: Chapters 1, 2 and 7.
Laboratory Component:
1. Develop a registration page for student enrolment as done in Module 2 but without page refresh using AJAX.
2. Develop a search application in Django using AJAX that displays courses enrolled by a student being searched.
Teaching-Learning Process
1. Demonstration using Visual Studio Code
2. PPT/Prezi Presentation for Architecture and Design Patterns
3. Live coding of all concepts with simple examples
4. Case Study: Apply the use of AJAX and jQuery for development of EMI calculator.
ET
5. Julia Elman, Mark Lavin, Light weight Django, David A. Bell, 1st Edition, Oreily Publications, 2014
Weblinks and Video Lectures (e-Resources):
1. MVT architecture with Django: https://freevideolectures.com/course/3700/django-tutorials
2. Using Python in Django: https://www.youtube.com/watch?v=2BqoLiMT3Ao
3. Model Forms with Django: https://www.youtube.com/watch?v=gMM1rtTwKxE
4. Real time Interactions in Django: https://www.youtube.com/watch?v=3gHmfoeZ45k
5. AJAX with Django for beginners: https://www.youtube.com/watch?v=3VaKNyjlxAU
Activity Based Learning (Suggested Activities in Class)/ Practical Based learning 1. Real world problem solving -
applying the Django framework concepts and its integration with AJAX to develop any shopping website with admin and
user dashboards.
Short Preamble on Full Stack Web Development:
Website development is a way to make people aware of the services and/or products they are offering,
understand why the products are relevant and even necessary for them to buy or use, and highlight the
JI
striking qualities that set it apart from competitors. Other than commercial reasons, a website is also
needed for quick and dynamic information delivery for any domain. Development of a well-designed,
informative, responsive and dynamic website is need of the hour from any computer science and related
engineering graduates. Hence, they need to be augmented with skills to use technology and framework
which can help them to develop elegant websites. Full Stack developers are in need by many
companies, who knows and can develop all pieces of web application (Front End, Back End and
business logic). MVT based development with Django is the cutting-edge framework for Full Stack
A
Web Development. Python has become an easier language to use for many applications. Django based
framework in Python
helps a web developer to utilize framework and develop rapidly responsive and secure web applications.
A
JI
ET
Module-1: MVC based Web Designing
Web Frameworks:
A web framework is a software framework designed to aid in the development of web applications by
providing reusable code, components, and tools that streamline the process. Web frameworks typically
follow the model-view-controller (MVC) architecture or a similar pattern, which helps in organizing code
and separating concerns.
Examples:
ET
1. Django (Python): Django is a high-level web framework for Python that follows the MVC pattern. It
provides a robust set of features for building web applications, including an ORM, URL routing,
form handling, session management, and a built-in admin interface.
2. Flask (Python): Flask is a lightweight web framework for Python that is designed to be simple and
easy to use. It provides essential features for building web applications, such as URL routing,
template rendering, and support for extensions.
3. Ruby on Rails (Ruby): Ruby on Rails is a popular web framework for Ruby that follows the MVC
pattern. It emphasizes convention over configuration and includes features like ActiveRecord
(ORM), URL routing, form helpers, and built-in support for testing.
4. Express.js (JavaScript/Node.js): Express.js is a minimal and flexible web framework for Node.js
JI
that is used for building web applications and APIs. It provides a simple yet powerful API for
defining routes, middleware, and handling HTTP requests and responses.
5. ASP.NET Core (C#): ASP.NET Core is a cross-platform web framework for building modern,
cloud- based web applications using C#. It includes features like MVC pattern support, middleware
pipeline, dependency injection, and built-in support for authentication and authorization.
A
The Model View Controller (MVC) design pattern specifies that an application consists of a data model,
presentation information, and control information. The pattern requires that each of these be separated into
different objects.
● The MVC pattern separates the concerns of an application into three distinct components, each
responsible for a specific aspect of the application’s functionality.
● This separation of concerns makes the application easier to maintain and extend, as changes to
one component do not require changes to the other components.
1. Model
ET
The Model component in the MVC (Model-View-Controller) design pattern represents the data and
JI
business logic of an application. It is responsible for managing the application’s data, processing business
rules, and responding to requests for information from other components, such as the View and the
Controller.
2. View
A
Displays the data from the Model to the user and sends user inputs to the Controller. It is passive and does
not directly interact with the Model. Instead, it receives data from the Model and sends user inputs to the
Controller for processing.
3. Controller
Controller acts as an intermediary between the Model and the View. It handles user input and updates the
Model accordingly and updates the View to reflect changes in the Model. It contains application logic, such
as input validation and data transformation.
Communication between the components
This below communication flow ensures that each component is responsible for a specific aspect of the
application’s functionality, leading to a more maintainable and scalable architecture
■
ET
decides how to respond.
Controller Updates Model:
The Controller updates the Model based on the user input or application
logic. Model Notifies View of Changes:
■ If the Model changes, it notifies the
View. View Requests Data from Model:
■ The View requests data from the Model to update its
display. Controller Updates View:
The Controller updates the View based on the changes in the Model or in response to user
JI
input. View Renders Updated UI:
■ The View renders the updated UI based on the changes made by the Controller.
Django Evolution
The evolution of Django, a popular web framework for building web applications in Python, has been
A
marked by significant milestones and improvements over the years. Here's a brief overview of its evolution:
1. Initial Release (2005): Django was originally developed by Adrian Holovaty and Simon Willison while
working at the Lawrence Journal-World newspaper. It was first released as open-source software in
July 2005, with the goal of enabling developers to build web applications quickly and efficiently.
2. Version 0.90 (2006): The first official release of Django (version 0.90) occurred in September 2006.
This version introduced many of the core features that Django is known for, including its ORM
(Object- Relational Mapping) system, its templating engine, and its admin interface.
3. Stable Releases and Growth (2007-2010): Over the next few years, Django continued to grow in
popularity and maturity. The development team released several stable versions, adding new features,
improving performance, and enhancing documentation.
4. Django 1.0 (2008): A significant milestone in Django's evolution was the release of version 1.0 in
September 2008. This marked the stabilization of the framework's API and signaled Django's readiness
for production use in a wide range of applications.
5. Django 1.x Series (2008-2015): The 1.x series of Django brought further refinements and
enhancements to the framework. These included improvements to the ORM, support for more database
backends, enhancements to the admin interface, and better support for internationalization and
localization.
ET
6. Django 1.11 LTS (2017): Django 1.11 was designated as a Long-Term Support (LTS) release, meaning
it would receive security updates and bug fixes for an extended period. LTS releases are particularly
important for organizations that require stability and long-term support for their Django applications.
7. Django 2.0 (2017): Django 2.0, released in December 2017, introduced several major changes,
including support for Python 3.4 and higher as well as dropping support for Python 2.x. It also
introduced asynchronous views and other improvements.
8. Django 3.x Series (2019-2022): The 3.x series of Django continued to build on the improvements
introduced in Django 2.0. It further refined support for asynchronous views, introduced new features
such as path converters, and continued to improve performance and security.
JI
9. Django 4.0 (2022): Django 4.0, released in December 2022, brought significant changes and
improvements, including support for Python 3.10 and higher as well as dropping support for older
Python versions. It also introduced stricter settings, improved model inheritance, and other
enhancements.
A
URLs
In Django, URLs are defined in the urls.py file. This file contains a list of URL patterns that map to views.
A URL pattern is defined as a regular expression that matches a URL. When a user requests a URL, Django
goes through the list of URL patterns defined in the urls.py file and finds the first pattern that matches the
URL. If no pattern matches, Django returns a 404 error.
The urls.py file provides a way to map a URL to a view. A view is a Python callable that takes a request and
returns an HTTP response. To map a URL to a view, we can create a urlpatterns list in the urls.py file. Each
element of the list is a path() or re_path() function call that maps a URL pattern to a view.
Here is an example of a simple urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
In this example, we have three URL patterns. The first pattern ('') matches the home page, and maps to the
index view. The second pattern ('about/') matches the about page, and maps to the about view. The third
pattern ('contact/') matches the contact page, and maps to the contact view.
Django also allows us to capture parts of the URL and pass them as arguments to the view function. We can
Views ET
capture parts of the URL by placing them inside parentheses in the URL pattern. For example, the
following URL pattern captures an integer id from the URL:
path('post/<int:id>/', views.post_detail, name='post_detail'),
In this example, the view function views.post_detail() takes an integer id as an argument.
Once Django has found a matching URL pattern, it calls the associated view function. A view function
takes a request as its argument and returns an HTTP response. The response can be a simple text message,
an HTML page, or a JSON object.
Here is an example of a simple view function:
JI
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello, world!')
In this example, the index view function takes a request object as its argument and returns an HTTP
A
response with the message "Hello, world!".
Views can also render HTML templates. Templates allow developers to separate the presentation logic from
the business logic. Here is an example of a view that renders an
1. URL Patterns: URLconfs consist of a collection of URL patterns, each of which associates a URL
2. Regular Expression Matchers: Django's URL dispatcher uses regular expression matching to
determine which view function should handle an incoming request based on the requested URL.
When a request comes in, Django compares the URL against each URL pattern in the URLconf until
it finds a match.
3. Modular Structure: URLconfs can be organized hierarchically, allowing you to include other
ET
JI
A
reusable applications that can be easily integrated into different projects. By providing well-defined
APIs and extension points, Django promotes loose coupling between applications, enabling greater
flexibility and scalability.
Django Exceptions & Errors
There are multiple packages for developer’s use. These packages may/ may not come in your use-case. For
the matter, the 1st package we are going to discuss is for those developers who are writing their own Python
scripts. These developers customize Django at a low level.
ET
1. django.core.exceptions Package
JI
This package provides us with low-level exceptions. It enables us to define new rules for our Django
project. We can load models, views in our own defined ways.
In the screenshot below, we can see the list of exceptions provided by this package.
1.1. AppRegistryNotReady
ET
This error occurs when the application model is imported before the app-loading process.
When we start our Django server, it first looks for settings.py file.
Django then installs all the applications in the list INSTALLED_APPS. Here, is a part of that process.
JI
App registry in brief:
When Django project starts, it generates an application registry. It contains the information in settings.py
and some more custom settings. This registry will keep record and install all the important components.
A
This registry contains settings-config of all apps inside INSTALLED_APPS. It is the first kernel of your Django
project. To use any app or submodule in your project, it has to load-in here first.
It is useful in exception catching when developing your own scripts. It may not occur when using default
Django files.
1.2. ObjectDoesNotExist
This exception occurs when we request an object which does not exist. It is the base class for all the
DoesNotExist Errors.
Brief on get():
get() is an important method used to return data from the server. This method returns the object when
found. It searches the object on the basis of arguments passed in the get(). If the get() does not find any
object, it raises this error.
1.3. EmptyResultSet
This error is rare in Django. When we generate a query for objects and if the query doesn’t return any
results, it raises this error.
1.4. FieldDoesNotExist
ET
The error is rare because most of the queries return something. It can be a false flag, but for custom lookups
This one is clear from its name. When a requested field does not exist in a model, this meta.get_field()
method raises this exception.
Meta.get_field() method mediates between views and models. When the model objects are in view
functions, Django uses this method for searching the fields. This method looks for the requested field in
JI
super_models as well. It comes in handy when we have made some changes to models.
1.5. MultipleObjectsReturned
When we expect a query to return a single response/ object but it returns more than one object, then Django
raises this exception.
A
The MultipleObjectsReturned is also an attribute of models. It is necessary for some models to return
multiple objects but for others, it cannot be more than one. This exception helps us to get more control over
model data.
1.6. SuspiciousOperation
It is one of the security classes of Django. Django raises this error when it has detected any malicious
activity from the user. This exception has many subclasses which are helpful in taking better security
measures.
When anyone modifies the session_data, Django raises this exception. Even when there is a modification in
There are many subclasses, dealing with very particular problems. These subclasses are:
● DisallowedHost
● DisallowedModelAdminLookup
● DisallowedModelAdminToField
● DisallowedRedirect
● InvalidSessionKey
● RequestDataTooBig
● SuspiciousFileOperation
● SuspiciousMultipartForm
ET
● SuspiciousSession
● TooManyFieldsSent
As we can see, all of them are very particular in some kind of data defect. These exceptions can detect
various types of activities on the server. They have helped a lot of developers to build reliable and secure
applications.
1.7. PermissionDenied
This exception is the clearest of all. You must have dealt with this exception while working on static files.
JI
Django raises this error when we store our static files in a directory which is not accessible.
You can raise this using the try/ except block but it will be more fun, the static files way. To raise it, change
static folder settings to hidden or protected.
1.8. ViewDoesNotExist
A
We all have experienced this one. Websites have a very evolving frontend design and there are frequent
modifications which can lead to some faulty urls.
Django checks for all urls and view function by default. If there is something wrong, the server will show an
error.
But we can also raise this error when urls-config can’t get the view to load. It is a problem which occurs
while using relative URL addressing.
Django is very useful at times. It raises this exception when an unused middleware is present in
MIDDLEWARES list. It’s like the caching middleware. Whenever we have not implemented caching on
our website, it will throw this exception.
All the middlewares present in our settings.py are utilized. Most of them are there for the admin app. You
can see in the below image that Django comes with pre-installed middlewares that we may require in our
application.
ET
JI
1.10. ImproperlyConfigured
You must have encountered this exception when configuring your first project. This exception is for the
A
main settings.py file. If there are some incorrect settings in the main settings then this error will raise. It can
also come up if the middlewares or modules do not load properly.
1.11. FieldError
We raise field errors when models have some errors. For example: using the same name in a class is correct
syntactically but it can be a problem for Django Models. Therefore, the exceptions will check for these
kinds of things.
Cases like:
● Fields in a model defined with the same name
● Infinite loops caused by wrong ordering
● Invalid use of join, drop methods
● Fields name may not exist, etc.
1.12. ValidationError
We used the validation error in validating the form data. This class is a sub-class of django.core.exceptions
class. It is extensively used to check data correctness. It will match the data with the model field or forms
field. And, it ensures that no security threat is there due to illegal characters in user-input.
There can be validation errors which do not belong to any particular field in Django. They are
NON_FIELD_ERRORS.
This class is a major part of urls.py for defining urls. We import our path function from urls class.
django.urls is one of the core classes of Django without which it might not function. This class also
provides some exceptions:
JI
2.1. Resolver404
We raise this exception if the path() doesn’t have a valid view to map. The Resolver404 shows us the error
page. It is django.http.Http404 module’s subclass.
A
2.2. NoReverseMatch
It is a common occurrence. When we request for a URL which is not defined in our urls-config, we get this
error. We all have seen that one page.
3. Database Exceptions
ET
This exception is also raised by django.urls module. It applies to regular expressions as well.
We can import these exceptions from django.db module. The idea behind this implementation is:
JI
Django wraps the standard database exceptions. And, when it happens, our Python code can correspond
with the database exception. That makes it easy to deal with database exceptions in Python at a certain
level.
The exception wrappers provided by Django work in the same way as Python database API.
A
The errors are:
● InterfaceError
● DatabaseError
● DataError
● IntegrityError
● InternalError
● ProgrammingError
● NotSupportedError
● Database is not found
● Interface is not there
● Database is not connected
● Input data is not valid etc.
4. Http Exceptions
We used this class in our first views. The HttpResponse is a sub-class of django.http class. The module provides
some exceptions and special responses.
UnreadablePostError - This exception occurs when a user uploads a corrupt file or cancels an upload. In
ET
both cases, the file received by the server becomes unusable.
5. Transaction Exceptions
A transaction is a set of database queries. It contains the smallest queries or atomic queries. When an error
occurs at this atomic level, we resolve them by the django.db.transaction module.
There are errors like TransactionManagementError for all transaction-related problems with the database.
6. Python Exceptions
JI
Django is a Python framework. Of course, we get all the pre-defined exceptions of Python as well. Python
has a very extensive library of exceptions. And, you can also add more modules according to use-case.
Django
A
Django Tutorial provides basic and advanced concepts of Django. Our Django Tutorial is designed for beginners
and professionals both.
Our Django Tutorial includes all topics of Django such as introduction, features, installation, environment
setup, admin interface, cookie, form validation, Model, Template Engine, Migration, MVT etc. All the
topics are explained in detail so that reader can get enought knowledge of Django
Need some processing to be done on back-end side to interact with servers, we have
1. Servlets
2. PHP
3. Javascript
4. ASP
5. Python - Django - Python Web Framework
ET
JI
A
Fully loaded
Django includes various helping task modules and libraries which can be used to handle common Web
development tasks. Django takes care of user authentication, content administration, site maps, RSS feeds
Versatile
Django is versatile in nature which allows it to build applications for different-different domains. Now a
days, Companies are using Django to build various types of applications like: content management systems,
social networks sites or scientific computing platforms etc.
ET
2. Form Validation - easy way to validate data submitted via a forms, check for correct format also
3. User Authentication - Inbuilt authentication system
JI
4. Data Serialization - allow developers to easily convert data into formats like JSON to easily transfer
it to the web .
Web application - some software running on the web browser over the internet.
A
Restful Web API - system that will provide data on proper request from the client.
PYTHON SETUP
4. Install Django
ET
JI
A
This above command will create a project folder. With some default file and another folder with the
same name.
ET
JI
A
Once the requested URL is mapped, Django will move to views.py file and call a view (Function), which
takes a web request and returns a web response. And the response back to the user
ET
Now navigate to views.py and create a home function.
JI
Now, to include the new app to our main project, do the change in the main project’s urls.py file as, include
the below line
A
Save and run the app using the “python manage.py runserver” command, then click on the link or reload
the browser. You will the message that need to displayed
Program 1
Develop a Django app that displays current date and time in server
views.py
ET
JI
Open urls.py in main project folder
A
PROGRAM 2
Develop a Django app that displays date and time four hours ahead and four hours before as an offset
of current date and time in server.
views.py
ET
JI
A
urls.py
A
JI
ET
Module-2: Django Templates and Models
MVT Structure has the following three parts –
Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is
the logical data structure behind the entire application and is represented by a database (generally relational
databases such as MySql, Postgres).
View: The View is the user interface — what you see in your browser when you render a website. It is
represented by HTML/CSS/Javascript and Jinja files.
Template: A template consists of static parts of the desired HTML output as well as some special syntax
TEMPLATES
ET
describing how dynamic content will be inserted.
Django provides a convenient way to generate dynamic HTML pages by using its template system.
A template consists of static parts of the desired HTML output as well as some special syntax describing how
dynamic content will be inserted.
Why we need separate urls.py for multiple apps, because it will be isolated and the changes made in
one will not affect the other.
JI
Django’s template language (DTL) is designed to strike a balance between power and ease. It’s designed
to feel comfortable to those used to working with HTML.
It is possible to added additional styles to my webpage like heading, image, and so on. Which can be done as
below. For example
A
Writing tags directly in the HTTPresponse will not be an efficient way when it comes to a big page or project.
In an HTML file, we can't write python code because the code is only interpreted by the python interpreter
not the browser.
web pages.
ET
We know that HTML is a static markup language, while Python is a dynamic programming language.
Django template engine is used to separate the design from the python code and allows us to build dynamic
Now create a new folder “Webpages” and create a new HTML file.
EXAMPLE 1
Index1.html
JI
A
ET
JI
urls.py
Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can
be created or you can use locals() to pass all local variable declared in the view.
EXAMPLE 2
ET
A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view
in the third parameter of the render function.
Index1.html
JI
views.py
A
In views.py {{subject}}, the double brackets means that the code is dynamic, similar to PHP.
EXAMPLE 3
ET
To change the background color
A wild Jinja has appeared, Jinja2 specifically. Jinja is a Python templating engine, aimed at helping you to
do dynamic things with your HTML like passing variables, running simple logic, and more! With Jinja, you
will notice we are using {% %}, this denotes logic. For variables, you will see {%{% }}. The use of block
content and endlock is one of the two major ways of incorporating templates within templates. This method
is generally used for header/template combinations, but there is another you could use that I will show later.
JI
Next, let's create another HTML file that will serve as whatever will fill this block content.
A
Color.html
Index1.html
ET
JI
A
Filters
They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.
Some examples −
views.py
def fliters_ex(request):
username = "django" ET
current_date = datetime.now().date()
current_time = datetime.now().time()
email = "[email protected]"
context = {
JI
'current_date': current_date,
'current_time': current_time,
'username': username,
A
'email': email,
ET
JI
urls.py
A
urls.py - Main project
ET
JI
A
Tags
Tags lets you perform the following operations: if condition, for loop, template inheritance and more.
for
PROGRAM 1
Develop a simple Django app that displays an unordered list of fruits and ordered list of selected students
for an event
Student_tag.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fruits</h1>
<ul>
ET
<title>Event Details</title>
JI
{% for fruit in fruits %}
{% endfor %}
</ul>
A
<h1>Selected Students</h1>
<ol>
ET
JI
A
views.py
ET
JI
A
urls.py
ET
JI
A
The MVT (Model View Template) is a software design pattern. It is a collection of three important
AY: 2023 – 24 14
components: Model View and Template.
The Model helps to handle databases. It is a data access layer which handles the data.
The View is used to execute the business logic and interact with a model to carry data and render a template.
The Template is a presentation layer which handles the User Interface part completely.
ET
Models - will work with Data
Template inheritance allows you to build a base “skeleton” template that contains all the common elements
of your site and defines blocks that child templates can override.
EXAMPLE 1
A
views.py
AY: 2023 – 24 15
urls.py
ET
JI
A
Inh_news.html
ET
JI
A
Inh_news_article.html
Inh_base.html
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
ET
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
JI
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
A
{% endblock %}
</div>
<div id="content">
</div>
</body>
CONFIGURING DATABASE
● PostgreSQL
● MariaDB
● MySQL
● Oracle
● SQLite
ET
As first step we need to download a MySQL workbench through the below link
After installing Django and setting up MySQL, you need to configure your Django project to use the
JI
MySQL database. Open your Django project’s settings.py file, usually located inside the project folder.
Look for the DATABASES setting and update it with the MySQL configuration:
A
ET
JI
A
Module-3: Django Admin Interfaces and Model Forms
ET
Customer class and customer objects
JI
A
● PostgreSQL
● MariaDB
● MySQL
● Oracle
● SQLite
ET
Django officially supports the following databases:
Once installed, open pgadmin, then click on the server and give the password (to be set during the time of
installation) to access.
A
Now create a new database
ET
JI
A
Migration of Models
ET
We can check the different model in https://docs.djangoproject.com/en/5.0/ref/models/fields/
<!doctype html>
A
<html lang="en">
<head>
<meta charset="utf-8">
ET
Open the link http://127.0.0.1:8000/
ET
JI
MIGRATION OF DATABASE
A
Now to access the admin page we need to create a super user using the below command
ET
JI
Modify the index.html which will fetch the datas from the Student Table
A
<!-- Bootstrap CSS -->
<title>Hello, world!</title>
</head>
<body>
<h1>Club</h1>
{% for x in obj %}
<div class="row">
ET
<div class="com-lg-5 col-md-5 col-12">
JI
{{x.name}}
</div>
{{x.des}}
A
</div>
</div>
{% endfor %}
</div>
</div>
ET
Create a static and two sub folder image and css inside the project.
ET
JI
A
Style.css
ET
JI
Django Forms
A
Forms are used for taking input from the user in some manner and using that information for
logical operations on databases. For example, Registering a user by taking input such as his
name, email, password, etc.
Django maps the fields defined in Django forms into HTML input fields. Django handles three
distinct parts of the work involved in forms:
class ContactForm(forms.Form):
name = forms.CharField(required=True)
email = forms.EmailField(required=True)
message = forms.CharField(widget=forms.Textarea)
Copy
This is just a basic example, but you can add additional fields and built-in validations to ensure that the user
inputs correct data:
from django import forms
from django.core.validators import EmailValidator
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
def contact(request):
ET
JI
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form data
pass
return redirect('success')
A
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
def success(request):
return HttpResponse('Success!')
form template.
ET
JI
A
To use the view function we created, you’ll also need to map a URL to the view function to create a
webpage or endpoint accessible via the URL.
that this code should go to the file called myproject/urls.py
from django.urls import path
from myproject.views import contact, success
ET
JI
A
ET
JI
A
After that, open your web browser and enter this URL http://127.0.0.1:8000/contact/
ET
JI
A
It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form
without writing HTML code.
We have a model containing various fields, we don't need to repeat the fields in the form file.
For this reason, Django provides a helper class which allows us to create a Form class from a Django
ET
JI
A
6. model = Student
7. fields = " all "
//views.py
from django.shortcuts import render
from myapp.form import StuForm
def index(request):
stu = EmpForm()
1. <!DOCTYPE html>
ET
2. <html lang="en">
JI
3. <head>
4. <meta charset="UTF-8">
5. <title>Index</title>
6. </head>
7. <body>
A
8. <form method="POST" class="post-form">
9. {% csrf_token %}
10. {{ form.as_p }}
11. <button type="submit" class="save btn btn-default">Save</button>
12. </form>
13. </body>
14. </html>
Run Server
Run the server by using python manage.py runserver command.
ET
Configuring URLs in Django
URLs, or Uniform Resource Locators, are essential for web applications as they define the address of each
resource within your application. In Django, URLs are used to map user requests to appropriate views,
which in turn render the correct templates and data. Django's URL handling is designed to be flexible, easy
JI
to configure, and scalable.
To configure URLs in Django, you need to create URL patterns or routes that define the mapping between
URLs and views. Here are the steps to create and configure URL patterns:
A
Step 1: Define URL Patterns in your App
In your Django app, create a new Python module called urls.py if it doesn't already exist. Inside this file,
you will define all the URL patterns for this specific app. To do this, you need to import the necessary
modules, create a variable called urlpatterns, and add the URL patterns to it.
In this example, we import the path function from django.urls and the views module from the current
ET
directory. Then, we define two URL patterns: one for the home page and another for the about page. The
first argument to the path function defines the URL pattern, the second argument specifies the view
function that should be called when the pattern is matched, and the name parameter assigns a name to the
URL pattern for easy referencing later on.
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
In this example, we import the include function and add a new URL pattern that includes the URLs from
the myapp.urls module. This means that all the URLs defined in myapp.urls will now be accessible with the
prefix myapp/.
When configuring URLs in Django, using views and URL namespaces can make your application more
organized and maintainable. Here are some tips:
● Use Function-based Views or Class-based Views: Django supports both function-based views and
class-based views. Function-based views are simple Python functions that take a request object and
ET
return a response object, while class-based views are more structured and provide greater flexibility
and reusability. Choose the one that best suits your needs and coding style.
● Use URL Namespaces: URL namespaces allow you to group related URL patterns under a common
prefix, making it easier to manage and reference them. To use URL namespaces, add an app_name
variable in your app's urls.py file and use the include function with the namespace parameter in your
project's urls.py file.
In conclusion, configuring URLs in Django is an essential skill for software developers working on web
applications. By following the guidelines and best practices outlined in this tutorial, you can create a well-
organized, maintainable, and user-friendly application. This knowledge will also be valuable for remote
Python developers who are working on Django projects.
URL Dispatchers - Including other URL
In Django, the URL dispatcher is a core component responsible for matching incoming HTTP requests with
the corresponding view functions. It helps Django determine which view function should be called based on
the requested URL.
How it works:
1. Incoming Request: When a user sends a request to your Django application, Django's URL
dispatcher examines the URL provided in the request.
2. URL Patterns: Django's URL dispatcher then compares the requested URL against a list of
URL patterns defined in your URL configuration.
ET
3. Match: If the requested URL matches any of the URL patterns, Django calls the associated
view function.
4. Response: The view function processes the request and returns an HTTP response, which
Django sends back to the user's browser.
Let's create a simple Django project called url_dispatcher_example with two apps: articles and blog. We'll
demonstrate how to use the URL dispatcher to include URL configurations from both apps.
ET
JI
blog App-Level URL Configuration (blog/urls.py):
A
Step 3: Define Views
ET
Views for blog App (blog/views.py):
JI
A
ET
JI
A
A
JI
ET
MODULE - 4 - Generic Views and Django State Persistence
ET
Key Benefits of Using Generic Views
1. Code Reusability: Generic Views encapsulate common API patterns, so you can reuse them across
multiple endpoints and models. This reduces code duplication and makes your codebase more
maintainable.
2. Consistency: DRF’s Generic Views follow a consistent naming convention and structure, which
improves the overall organization of your code and makes it easier for other developers to
understand and work with.
3. Saves Time: Writing CRUD (Create, Read, Update, Delete) views for every model can be time-
consuming. Generic Views save you time by providing pre-implemented views for these
JI
operations.
4. Flexibility: While Generic Views provide sensible defaults, they are highly customizable. You can
easily override their behavior to suit your specific requirements.
urls.py
ET
JI
A
views.py
ET
JI
A
class BookCreateView(CreateView):
model = Book
template_name = 'book_form.html'
success_url = reverse_lazy('book_list')
class BookUpdateView(UpdateView):
model = Book
ET
template_name = 'book_form.html'
class BookDeleteView(DeleteView):
A
model = Book
template_name = 'book_confirm_delete.html'
success_url = reverse_lazy('book_list')
class AboutUsView(TemplateView):
ET
JI
Create Templates
Create templates for each view:
Book_list .html
Book_details.html
ET
JI
A
Book_from.html
ET
JI
A
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Book</title>
</head>
<body>
<h1>Delete Book</h1>
<form method="post">
{% csrf_token %}
ET
<p>Are you sure you want to delete "{{ object.title }}"?</p>
</form>
JI
<a href="{% url 'book_list' %}">Cancel</a>
</body>
</html>
A
Contact.html
About_us.html
ET
JI
A
Migrate the model and then run the code follow the below commands
A
JI
ET
All the changes will be reflected to the database (PostgreSQL)
ET
JI
MIME types (IANA media types)
A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature
and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's
A
RFC 6838
The Internet Assigned Numbers Authority (IANA) is responsible for all official MIME types
A MIME type most commonly consists of just two parts: a type and a subtype, separated by
a slash (/) — with no whitespace between:
type/subtype
The type represents the general category into which the data type falls, such as video or text.
The subtype identifies the exact kind of data of the specified type the MIME type represents.
For example, for the MIME type text, the subtype might be plain (plain text), html (HTML
source code), or calendar (for iCalendar/.ics) files.
Types
1.
ET
discrete - iscrete types are types which represent a single file or medium, such as a single text or
music file, or a single video.
Image Image or graphical data including both bitmap and vector still images as well as animated versions of
still image formats such as animated GIF or APNG. Common examples are image/jpeg, image/png, and
image/svg+xml.
A
Model Model data for a 3D object or scene. Examples include model/3mf and model/vrml
Text-only data including any human-readable content, source code, or textual data such as comma-separated
value (CSV) formatted data. Examples include: text/plain, text/csv, and text/html.
2. Multipart - A multipart type represents a document that's comprised of multiple component parts,
each of which may have its own individual MIME type; or, a multipart type may encapsulate multiple files
being sent together in one transaction. For example, multipart MIME types are used when attaching
multiple files to an email.
Message - message/rfc822 (for forwarded or replied-to message quoting) and message/partial to allow breaking a
large message into smaller ones automatically to be reassembled by the recipient.
Multipart - Data that consists of multiple components which may individually have different MIME types.
Examples include multipart/form-data (for data produced using the FormData API)
Producing CSV
ET
CSV is a simple data format usually used by spreadsheet software. It’s basically a series of table rows, with
each cell in the row separated by a comma (CSV stands for comma-separated values). For example, here’s
some data on “unruly” airline passengers in CSV format:
views.py
JI
A
urls.py (Project File)
ET
JI
A
Run the project and check in http://127.0.0.1:8000/csv/ , your CSV file will be downloaded.
ET
Dynamic CSV using Database
views.py
JI
A
models.py
ET
JI
A
GENERATING PDF
Portable Document Format (PDF) is a format developed by Adobe that’s used to represent printable
documents, complete with pixel-perfect formatting, embedded fonts, and 2D vector graphics. You can think
of a PDF document as the digital equivalent of a printed document; indeed, PDFs are often used in
distributing documents for the purpose of printing them. You can easily generate PDFs with Python and
Django thanks to the excellent open source ReportLab library (http://www.reportlab.org/rl_toolkit.html).
The advantage of generating PDF files dynamically is that you can create customized PDFs for different
purposes – say, for different users or different pieces of content.
For example, your humble authors used Django and ReportLab at KUSports.com to generate customized,
printer-ready NCAA tournament brackets.
ET
Installing ReportLab Before you do any PDF generation, however, you’ll need to install ReportLab.
views.py
JI
A
response = HttpResponse(content_type='application/pdf')
p = canvas.Canvas(response)
p.setFont("Times-Roman", 12)
y_position = 700 ET
# Write student information to the PDF
y_position -= 20
ET
JI
Configure the app and database in the settings.py file as below.
A
Now click on the above server address and give as “http://127.0.0.1:8000/pdf”, automatically your PDf will
It will generate the student.pdf file as below
Other Possibilities
ET
There’s a whole host of other types of content you can generate in Python. Here are a few more ideas and
some
JI
pointers to libraries you could use to implement them:
ZIP files: Python’s standard library ships with the zipfile module, which can both read and write
compressed ZIP files. You could use it to provide on-demand archives of a bunch of files, or perhaps
compress large documents when requested. You could similarly produce TAR files using the standard
library’s tarfile module.
A
Plots and charts: There are a number of powerful Python plotting and charting libraries you could use to
produce on-demand maps, charts, plots, and graphs. We can’t possibly list them all, so here are a couple of
matplotlib (http://matplotlib.sourceforge.net/) can be used to produce the type of high-quality plots usually
generated with MatLab or Mathematica.
In general, any Python library capable of writing to a file can be hooked into Django. The possibilities are
immense.
Now that we’ve looked at the basics of generating non-HTML content, let’s step up a level of abstraction.
Django ships with some pretty nifty built-in tools for generating some common types of non-HTML
content.
ET
Django comes with a high-level syndication-feed-generating framework that makes creating RSS and Atom feeds easy.
RSS and Atom are both XML-based formats you can use to provide automatically updating “feeds” of your site’s content. Read more about
RSS at http://www.whatisrss.com/, and get information on Atom at http://www.atomenabled.org/.
To create any syndication feed, all you have to do is write a short Python class. You can create as many feeds as you want.
The high-level feed-generating framework is a view that’s hooked to /feeds/ by convention. Django uses the remainder of the URL (everything
after /feeds/) to determine which feed to return.To create a feed, you’ll write a Feed class and point to it in your URLconf.
JI
Initialization
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed',
A
{'feed_dict': feeds}
),
This line tells Django to use the RSS framework to handle all URLs starting with "feeds/". (You can change that "feeds/" prefix to fit your own
needs.)
This URLconf line has an extra argument: {'feed_dict': feeds}. Use this extra argument to pass the syndication framework the feeds that should
be published under that URL.
Django comes with a high-level syndication-feed-generating framework for creating RSS and Atom feeds.
Django also comes with a lower-level feed-generating API. Use this if you want to generate feeds outside of a web context,
or in some other lower-level way.
Overview¶
The high-level feed-generating framework is supplied by the Feed class. To create a feed, write a Feed class and point to an
instance of it in your URLconf.
Feed classes
ET
A Feed class is a Python class that represents a syndication feed. A feed can be simple (e.g., a “site news” feed, or a basic
feed displaying the latest entries of a blog) or more complex (e.g., a feed displaying all the blog entries in a particular
category, where the category is variable).
Feed classes subclass django.contrib.syndication.views.Feed. They can live anywhere in your codebase.
Instances of Feed classes are views which can be used in your URLconf.
A simple example
This simple example, taken from a hypothetical police beat news site describes a feed of the latest five news items:
JI
Create a new file feeds.py in you app
A
# Define your feed items here
return [
'link': 'http://127.0.0.1:8000/news/News-Item-1/',
},
}
ET
'title': 'News Item 2',
'link': 'http://127.0.0.1:8000/news/News-Item-2/',
return item['title']
return item['description']
ET
JI
A
One thing is left to do. In an RSS feed, each <item> has a <title>, <link> and <description>. We need to tell the
framework what data to put into those elements.
● For the contents of <title> and <description>, Django tries calling the methods item_title() and
item_description() on the Feed class. They are passed a single parameter, item, which is the object itself. These
are optional; by default, the string representation of the object is
used for both. If you want to do any special formatting for either the title or
description, Django templates can be used instead. Their paths can be specified with the title_template and
See a
○
complex
Feed.get_context_data(**kwargs)¶
ET
description_template attributes on the Feed class. The templates are rendered for each item and are passed two
template context variables:
○ {{ obj }} – The current object (one of whichever objects you returned in items()).
{{ site }} – A django.contrib.sites.models.Site object representing the current site. This is useful for {{
site.domain }} or {{ site.name }}. If you do not have the Django sites framework installed, this will be set
to a RequestSite object. See the RequestSite section of the sites framework documentation for more.
There is also a way to pass additional information to title and description templates, if you need to supply more than the
two variables mentioned before. You can provide your implementation of get_context_data method in your Feed subclass.
template.
JI
For example:
from mysite.models import Article
class ArticlesFeed(Feed):
description_template = "feeds/articles.html"
def items(self):
return Article.objects.order_by("-pub_date")[:5]
return context
● This method will be called once per each item in the list returned by items() with the following keyword arguments:
○ item: the current item. For backward compatibility reasons, the name of this context variable is {{ obj }}.
○ obj: the object returned by get_object(). By default this is not exposed to the templates to avoid confusion
with {{ obj }} (see above), but you can use it in your implementation of get_context_data().
○ site: current site as described above.
●
○
ET
request: current request.
The behavior of get_context_data() mimics that of generic views - you’re supposed to call super() to retrieve
context data from parent class, add your data and return the modified dictionary.
To specify the contents of <link>, you have two options. For each item in items(), Django first tries calling the
item_link() method on the Feed class. In a similar way to the title and description, it is passed it a single
parameter, item. If that method doesn’t exist, Django tries executing a get_absolute_url() method on that object.
Both get_absolute_url() and item_link() should return the item’s URL as a normal Python string. As with
get_absolute_url(), the result of item_link() will be included directly in the URL, so you are responsible for
doing all necessary URL quoting and conversion to ASCII inside the method itself.
For example, say your blog offers an RSS feed for every distinct “tag” you’ve used to categorize your
entries. It would be silly to create a separate Feed class for each tag; that would violate the Don’t Repeat
Yourself (DRY) principle and would couple data to programming logic.
A
Instead, the syndication framework lets you make generic feeds that return items based on information in the
feed’s URL.
The slug here is "tags". The syndication framework sees the extra URL bits after the slug – 'python' and 'cats'
– and gives you a hook to tell it what those URL bits mean and how they should influence which items get
published in the feed.
An example makes this clear. Here’s the code for these tag-specific feeds:
class TagFeed(Feed):
raise ObjectDoesNotExist
ET
return Tag.objects.get(tag=bits[0])
return obj.get_absolute_url()
A
return entries.order_by('-pub_date')[:30]
Here’s the basic algorithm of the RSS framework, given this class and a request to the URL
/feeds/tags/python/:
1. The framework gets the URL /feeds/tags/python/ and notices there’s an extra bit of URL after the slug.
It splits that remaining string by the slash character ("/") and calls the Feed class’s get_object() method,
passing it the bits.
['python', 'django'].
ET
2. get_object() is responsible for retrieving the given Tag object, from the given bits.
In this case, it uses the Django database API to retrieve the Tag. Note that get_object() should raise
django.core.exceptions.ObjectDoesNotExist if given invalid parameters. There’s no try/except around the
Tag.objects.get() call, because it’s not necessary. That function raises Tag.DoesNotExist on failure, and
Tag.DoesNotExist is a subclass of ObjectDoesNotExist. Raising ObjectDoesNotExist in get_object() tells
Django to produce a 404 error for that request.
3. To generate the feed’s <title>, <link>, and <description>, Django uses the title(), link(), and
description() methods. In the previous example, they were simple string class attributes, but this example
JI
illustrates that they can be either strings or methods. For each of title, link, and description, Django follows
this algorithm:
1. It tries to call a method, passing the obj argument, where obj is the object returned by get_object().
4. Finally, note that items() in this example also takes the obj argument. The algorithm for items is the
same as described in the previous step – first, it tries items(obj), then items(), and then finally an items class
attribute (which should be a list).
Full documentation of all the methods and attributes of the Feed classes is always available from the official
ET
JI
A
By default, the syndication framework produces RSS 2.0. To change that, add a feed_type attribute to your
Feed
class:
class MyFeed(Feed):
feed_type = Atom1Feed
Table 11-1.
Feed Class
ET
Note that you set feed_type to a class object, not an instance. Currently available feed types are shown in
Format
Enclosures
A
To specify enclosures (i.e., media resources associated with a feed item such as MP3 podcast feeds), use the
link = "/feeds/example-with-enclosures/"
def items(self):
return Song.objects.all()[:30]
return item.song_url
bytes) fields.
Language
ET
def item_enclosure_length(self, item):
This assumes, of course, that you’ve created a Song object with song_url and song_length (i.e., the size in
Feeds created by the syndication framework automatically include the appropriate <language> tag (RSS
2.0) or
JI
xml:lang attribute (Atom). This comes directly from your LANGUAGE_CODE setting.
URLs
The link method/attribute can return either an absolute URL (e.g., "/blog/") or a URL with the fully
qualified domain and protocol (e.g., "http://www.example.com/blog/"). If link doesn’t return the domain,
A
the syndication framework will insert the domain of the current site, according to your SITE_ID setting.
(See Chapter 16 for more on SITE_ID and the sites framework.)
Atom feeds require a <link rel="self"> that defines the feed’s current location. The syndication framework
populates this automatically.
Some developers like to make available both Atom and RSS versions of their feeds. That’s easy to do with
Django: just create a subclass of your feed class and set the feed_type to something different. Then update
your URLconf to add the extra versions. Here’s a full example:
class RssLatestEntries(Feed):
def items(self):
return Entry.objects.order_by('-pub_date')[:5]
feed_type = Atom1Feed
ET
class AtomLatestEntries(RssLatestEntries):
feeds = {
'rss': RssLatestEntries,
'atom': AtomLatestEntries,
A
urlpatterns = patterns('',
# ...
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed',
# ...
A sitemap is an XML file on your Web site that tells search engine indexers how frequently your pages
change and how “important” certain pages are in relation to other pages on your site. This information helps
search engines index your site.
For example, here’s a piece of the sitemap for Django’s Web site
ET
(http://www.djangoproject.com/sitemap.xml):
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.djangoproject.com/documentation/</loc>
<changefreq>weekly</changefreq>
JI
<priority>0.5</priority>
</url>
<url>
<loc>http://www.djangoproject.com/documentation/0_90/</loc>
A
<changefreq>never</changefreq>
<priority>0.1</priority>
</url>
...
For more on sitemaps, see http://www.sitemaps.org/.
The Django sitemap framework automates the creation of this XML file by letting you express this information
in
Python code. To create a sitemap, you just need to write a Sitemap class and point to it in your URLconf.
Installation
ET
setting. It’s in there by default, so you’ll need to change this only if you’ve changed that setting.
3. Make sure you’ve installed the sites framework (see Chapter 16).
Note
The sitemap application doesn’t install any database tables. The only reason it needs to go into
JI
INSTALLED_APPS is so the load_template_source template loader can find the default templates.
Initialization
To activate sitemap generation on your Django site, add this line to your URLconf:
A
This line tells Django to build a sitemap when a client accesses /sitemap.xml. Note that the dot character in
sitemap.xml is escaped with a backslash, because dots have a special meaning in regular expressions.
The name of the sitemap file is not important, but the location is. Search engines will only index links in
your sitemap for the current URL level and below. For instance, if sitemap.xml lives in your root directory,
it may reference any URL in your site. However, if your sitemap lives at /content/sitemap.xml, it may only
reference
The sitemap view takes an extra, required argument: {'sitemaps': sitemaps}. sitemaps should be a dictionary
that maps a short section label (e.g., blog or news) to its Sitemap class (e.g., BlogSitemap or NewsSitemap).
It may also map to an instance of a Sitemap class (e.g., BlogSitemap(some_var)).
Sitemap Classes
A Sitemap class is a simple Python class that represents a “section” of entries in your sitemap. For example,
one
Sitemap class could represent all the entries of your weblog, while another could represent all of the events
in your events calendar.
In the simplest case, all these sections get lumped together into one sitemap.xml, but it’s also possible to use
ET
the framework to generate a sitemap index that references individual sitemap files, one per section (as
described shortly).
Sitemap classes must subclass django.contrib.sitemaps.Sitemap. They can live anywhere in your code tree.
For example, let’s assume you have a blog system, with an Entry model, and you want your sitemap to
include all the links to your individual blog entries. Here’s how your Sitemap class might look:
return Entry.objects.filter(is_draft=False)
return obj.pub_date
Declaring a Sitemap should look very similar to declaring a Feed. That’s by design.
Like Feed classes, Sitemap members can be either methods or attributes. See the steps in the earlier “A
items (required): Provides list of objects. The framework doesn’t care what type of objects they are; all that
matters is that these objects get passed to the location(), lastmod(), changefreq(), and priority()
methods.
location (optional): Gives the absolute URL for a given object. Here, “absolute URL” means a URL that doesn’t
include the protocol or domain. Here are some examples:
Good: '/foo/bar/'
Bad: 'example.com/foo/bar/'
ET
Bad: 'http://example.com/foo/bar/'
If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned
JI
by items().
lastmod (optional): The object’s “last modification” date, as a Python datetime object.
A
changefreq (optional): How often the object changes. Possible values (as given by the Sitemaps
'always'
'hourly'
'weekly'
'monthly'
'yearly'
'never'
priority (optional): A suggested indexing priority between 0.0 and 1.0. The default priority of a page is
0.5; see the http://sitemaps.org/ documentation for more about how priority works.
Shortcuts
FlatPageSitemap
ET
The sitemap framework provides a couple convenience classes for common cases. These are described in the
sections that follow.
The django.contrib.sitemaps.FlatPageSitemap class looks at all flat pages defined for the current site and
creates an entry in the sitemap. These entries include only the location attribute – not lastmod, changefreq,
or priority.
JI
GenericSitemap
The GenericSitemap class works with any generic views (see Chapter 11) you already have.
To use it, create an instance, passing in the same info_dict you pass to the generic views. The only
requirement is that the dictionary have a queryset entry. It may also have a date_field entry that specifies a
A
date field for objects retrieved from the queryset. This will be used for the lastmod attribute in the generated
sitemap. You may also pass priority and changefreq keyword arguments to the GenericSitemap constructor
to specify these attributes for all URLs.
Here’s an example of a URLconf using both FlatPageSitemap and GenericSiteMap (with the hypothetical
Entry
info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
sitemaps = {
'flatpages': FlatPageSitemap,
urlpatterns = patterns('',
ET
'blog': GenericSitemap(info_dict, priority=0.6),
# the sitemap
(r'^sitemap\.xml$',
'django.contrib.sitemaps.views.sitemap',
A
{'sitemaps': sitemaps})
The sitemap framework also has the ability to create a sitemap index that references individual sitemap
files, one per each section defined in your sitemaps dictionary. The only differences in usage are as follows:
The django.contrib.sitemaps.views.sitemap view should take a section keyword argument. Here is what the
relevant URLconf lines would look like for the previous example:
(r'^sitemap.xml$',
'django.contrib.sitemaps.views.index',
{'sitemaps': sitemaps}),
(r'^sitemap-(?P<section>.+).xml$',
ET
'django.contrib.sitemaps.views.sitemap',
{'sitemaps': sitemaps})
This will automatically generate a sitemap.xml file that references both sitemap-flatpages.xml and
sitemap-blog.xml. The Sitemap classes and the sitemaps dictionary don’t change at all.
Pinging Google
JI
You may want to “ping” Google when your sitemap changes, to let it know to reindex your site. The framework
provides a function to do just that: django.contrib.sitemaps.ping_google().
ping_google() takes an optional argument, sitemap_url, which should be the absolute URL of your site’s
sitemap (e.g., '/sitemap.xml'). If this argument isn’t provided, ping_google() will attempt to figure out your
sitemap by performing a reverse lookup on your URLconf.
A
# ...
try:
ping_google()
except Exception:
ET
A more efficient solution, however, would be to call ping_google() from a cron script or some other
scheduled task. The function makes an HTTP request to Google’s servers, so you may not want to introduce
that network
Finally, if 'django.contrib.sitemaps' is in your INSTALLED_APPS, then your manage.py will include a new
command, ping_google. This is useful for command-line access to pinging. For example: