MODULE 4- FSD-Notes
MODULE 4- FSD-Notes
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Chapter 9
• Using Generic Views
• Generic Views of Objects
• Extending Generic Views
Chapter 11
• MIME Types
• Generating Non-HTML content like CSV and PDF
• Syndication feed framework
• Sitemap framework
Chapter 12
• Cookies
• Sessions
• Users and Authentication
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHAPTER 9
The direct_to_template view simply grabs information from the extra-parameters dictionary and uses that
information when rendering the view.
Because this generic view — and all the others — is a regular view functions like any other, we can
reuse it inside our own views.
They key is in the URLconf: we’re using the regular expression \w+ to match the page part of the URL,
and \w only accepts letters and numbers.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
The generic views really shine when it comes to presenting views of your database content. Because it’s
such a common task, Django comes with a handful of built-in generic views that make generating list
and detail views of objects incredibly easy.
Let’s start by looking at some examples of showing a list of objects or an individual object. We’ll be
using these models:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
This example puts Publisher.objects.all() in the URLconf, it will be evaluated only once (when the
URLconf is first loaded). Once you add or remove publishers, you’ll notice that the generic view
doesn’t reflect those changes until you reload the Web server.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
If we want to add another publisher page, we’d need another handful of lines in the URLconf.
4. Complex Filtering with Wrapper Functions
Another common need is to filter down the objects given in a list page by some key in the URL.
Earlier we hard-coded the publisher’s name in the URLconf, but what if we wanted to write a view
that displayed all the books by some arbitrary publisher? We can “wrap” the object_list generic view
to avoid writing a lot of code by hand. As usual, we’ll start by writing a URLconf:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHAPTER 11
MIME Types
A view function, or view for short, is simply a Python function that takes a Web request and returns a
Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or
an XML document, or an image…or anything, really.
A Django view function must
• Accept an HttpRequest instance as its first argument.
• Return an HttpResponse instance.
The key to returning non-HTML content from a view lies in the HttpResponse class, specifically the
mimetype constructor argument. By tweaking the MIME type, we can indicate to the browser that we’ve
returned a response of a different format.
For example, let’s look at a view that returns a PNG image. To keep things simple, we’ll just read the file
off the disk:
That’s it! If you replace the image path in the open() call with a path to a real image, you can use this
very simple view to serve an image, and the browser will display it correctly.
CSV
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:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
• The response is given the text/csv MIME type (instead of the default text/html). This tells browsers
that the document is a CSV file.
• The response gets an additional Content-Disposition header, which contains the name of the CSV file.
This header (well, the “attachment” part) will instruct the browser to prompt for a location to save the
file (instead of just displaying it). This file name is arbitrary; call it whatever you want. It will be used by
browsers in the Save As dialog.
• Hooking into the CSV-generation API is easy: just pass response as the first argument to csv.writer.
The csv.writer function expects a filelike object, and HttpResponse objects fit the bill.
• For each row in your CSV file, call writer.writerow, passing it an iterable object such as a list or tuple.
• The CSV module takes care of quoting for you, so you don’t have to worry about escaping strings with
quotes or commas in them. Just pass information to writerow(), and it will do the right thing.
NOTE –
This is the general pattern you’ll use any time you need to return non-HTML content: create an
HttpResponse response object (with a special MIME type), pass it to something expecting a file, and then
return the response.
1. Installing ReportLab
2. Writing Your View
3. Complex PDFs
4. Other Possibilities
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
1. Installing ReportLab
• For windows in django install - pip install reportlab
• For ubuntu in Django install - apt-get install python-reportlab
• Test your installation by importing it in the Pyth interactive interpreter: >>> import reportlab
• If that command doesn’t raise any errors, the installation worked.
A few notes are in order: Here we use the application/pdf MIME type. This tells browsers that the
document is a PDF file, rather than an HTML file. If you leave off this information, browsers will
probably interpret the response as HTML, which will result in scary gobbledygook in the browser
window.
• Hooking into the ReportLab API is easy: just pass response as the first argument to canvas.Canvas.
The Canvas class expects a filelike object, and HttpResponse objects fit the bill.
• All subsequent PDF-generation methods are called on the PDF object (in this case, p), not on
response.
• Finally, it’s important to call showPage() and save() on the PDF file (or else you’ll end up with a
corrupted PDF file)
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
3. Complex PDFs
If you’re creating a complex PDF document (or any large data blob), consider using the cStringIO
library as a temporary holding place for your PDF file. The cStringIO library provides a file-like
object interface that is written in C for maximum efficiency.
4. Other Possibilities
There’s a whole host of other types of content you can generate in Python. Here are a few more ideas
and some 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.
Dynamic images: The Python Imaging Library is a fantastic toolkit for producing images (PNG,
JPEG, GIF, and a whole lot more). You could use it to automatically scale down images into
thumbnails, composite multiple images into a single frame.
Plots and charts: There are a number of incredibly powerful Python plotting and charting libraries
you could use to produce on-demand maps, charts, plots, and graphs.
- matplotlib - can be used to produce the type of high-quality plots usually generated with MatLab
or Mathematica.
- pygraphviz - an interface to the Graphviz graph layout toolkit (http://graphviz.org/), can be used
for generating structured diagrams of graphs and networks.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
1. Initialization
2. A Simple Feed
3. A More Complex Feed
4. Specifying the Type of Feed
5. Enclosures
6. Language
7. URLs
8. Publishing Atom and RSS Feeds in Tandem
1. Initialization
• Add a URLconf to activate syndication feeds.
(r'^feeds/(?P.*)/$', '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. A Simple Feed
This simple example, taken from chicagocrime.org, describes a feed of the latest five news items:
• Use feed_dict to map feed slugs to Feed classes:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Note that you set feed_type to a class object, not an instance. Currently available feed types are
shown in Table
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
5. Enclosures
To specify enclosures (i.e., media resources associated with a feed item such as MP3 podcast feeds),
use the item_enclosure_url, item_enclosure_length, and item_enclosure_mime_type hooks, for
example:
6. Language
Feeds created by the syndication framework automatically include the appropriate tag (RSS 2.0) or
xml:lang attribute (Atom). This comes directly from your LANGUAGE_CODE setting.
7. 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, the syndication framework will insert the domain of the current
site, according to your SITE_ID setting.
Atom feeds require a <link rel="self"> that defines the feed’s current location. The syndication
framework populates this automatically, using the domain of the current site according to the
SITE_ID setting.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
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.
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.
1. Installation
2. Initialization
3. Sitemap Classes
4. Shortcut – FlatPageSitemap, GenericSitemap
5. Creating a Sitemap Index
6. Pinging Google
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
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
path(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
• The dot in sitemap.xml is escaped with a backslash.
3. Sitemap Classes
• Subclass django.contrib.sitemaps.Sitemap.
• Define methods and attributes such as items, lastmod, changefreq, priority.
6. Pinging Google
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().
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHAPTER 12
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.
1. 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
2. Getting and Setting Cookies in Django:
• Reading Cookies:
• Use the COOKIES attribute of HttpRequest to read cookies.
• Writing Cookies:
• Use the set_cookie() method of HttpResponse to set cookies.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
SESSIONS
• 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.
1. Enabling Sessions
2. Using Sessions in Views
3. Setting Test Cookies
4. Using Sessions Outside of Views
5. When Sessions Are Saved
6. Browser-Length Sessions vs. Persistent Sessions
7. Other Session Settings
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
1. Enabling Sessions
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
INSTALLED_APPS = [
'django.contrib.sessions',
request.session["fav_color"] = "blue"
fav_color = request.session["fav_color"]
del request.session["fav_color"]
if "fav_color" in request.session:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Django provides an easy way to test whether a user’s browser accepts cookies.
This split between set_test_cookie() and test_cookie_worked() is necessary due to the way cookies
work. When you set a cookie, you can’t actually tell whether a browser accepted it until the
browser’s next request.
It’s good practice to use delete_test_cookie() to clean up after yourself. Do this after you’ve
verified that the test cookie worked.
s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
session_data = s.get_decoded()
By default, Django saves the session to the database only if it has been modified:
request.session['foo'] = {} # Modified
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
2. Using Users
Anonymous User objects emulate some of this interface, but not all of it, so you should always check
user.is_authenticated() before assuming you’re dealing with a bonafide user object.
3. Logging In and Out
• Use auth.authenticate(username, password) to verify credentials.
• Check if a user is authenticated with request.user.is_authenticated()
• Use auth.login(request, user) to log in a user.
• Use auth.logout(request) to log out a user.
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
4. Limiting Access to Logged-in Users
The simple, raw way to limit access to pages is to check request.user.is_authenticated() and redirect
to a login page:
As a shortcut, you can use the convenient login_required decorator
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
# ...
login_required does the following:
• If the user isn’t logged in, redirect to /accounts/login/, passing the current absolute URL in the
query string as next, for example: /accounts/login/?next=/polls/3/.
• If the user is logged in, execute the view normally. The view code can then assume that the user is
logged in.
5. Limiting Access to Users Who Pass a Test
Limiting access based on certain permissions or some other test, or providing a different location for
the login view works essentially the same way.
user.permissions.add(permission1, permission2, ...)
user.permissions.remove(permission1, permission2, ...)
user.permissions.clear()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
6. Managing Users, Permissions, and Groups – creating a user,changing password, handling registration
• Admin interface provides an easy way to manage users and their permissions.
• Low-level APIs available for absolute control over user management.
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()
7. Using Authentication Data in Templates
• {{ user }} template variable for accessing the current user.
• {{ perms }} template variable for checking user permissions within templates.
Prepared By,
Ranjitha J
Assistant
ProfessorDept, of
ISE
SJB Institute of Technology