FSD Module4
FSD Module4
Module-04
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.
1. Simple URLconf
urlpatterns = patterns('',
(r'^about/$', direct_to_template, {'template': 'about.html'})
)
Explanation: direct_to_template is used to render about.html without additional view
code.
1
21CS62 | FULLSTACK DEVELOPMENT
Advanced Example: Dynamic Static Pages
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),
)
Explanation:
2. Advantages:
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.
3
21CS62 | FULLSTACK DEVELOPMENT
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.
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()
class Meta:
ordering = ['name']
4
21CS62 | FULLSTACK DEVELOPMENT
3. Specifying a Template:
You can explicitly specify the template to be used.
publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
}
urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)
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.
5
21CS62 | FULLSTACK DEVELOPMENT
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.
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:
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.
6
21CS62 | FULLSTACK DEVELOPMENT
Example:
publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
'template_object_name': 'publisher',
urlpatterns = patterns('',
7
21CS62 | FULLSTACK DEVELOPMENT
Template:
{% extends "base.html" %}
{% block content %}
<h2>Publishers</h2>
<ul>
{% endfor %}
</ul>
{% endblock %}.
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}
}
8
21CS62 | FULLSTACK DEVELOPMENT
Viewing Subsets of Objects
Example
apress_books = {
'template_name': 'books/apress_list.html'
urlpatterns = patterns('',
9
21CS62 | FULLSTACK DEVELOPMENT
Complex Filtering with Wrapper Functions
Example
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'^books/(\w+)/$', books_by_publisher),
10
21CS62 | FULLSTACK DEVELOPMENT
Performing Extra Work
import datetime
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),
# ...
11
21CS62 | FULLSTACK DEVELOPMENT
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'
return response
12
21CS62 | FULLSTACK DEVELOPMENT
MIME Types
1. Structure:
MIME types have a format: type/subtype.
Example: image/jpeg for JPEG images.
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.
13
21CS62 | FULLSTACK DEVELOPMENT
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
This header tells the client that the content is an HTML document.
14
21CS62 | FULLSTACK DEVELOPMENT
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.
6. Registration:
Official MIME types are registered with IANA (Internet Assigned Numbers
Authority).
15
21CS62 | FULLSTACK DEVELOPMENT
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
16
21CS62 | FULLSTACK DEVELOPMENT
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
17
21CS62 | FULLSTACK DEVELOPMENT
Generating PDFs with Django
1. PDF Format:
PDF (Portable Document Format) is used for printable documents with
precise formatting.
18
21CS62 | FULLSTACK DEVELOPMENT
Syndication Feed Framework
An RSS feed is a simple XML file that allows websites to distribute new content to their
audience in a standardized format. The term "RSS" can refer to "Really Simple Syndication"
or "Rich Site Summary," but both names emphasize the same goal: to simplify the process of
getting updates from websites you're interested in. Instead of manually checking for new posts
or new articles on various platforms, you can use an RSS feed reader to bring all this new
content straight to you.
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.
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:
19
21CS62 | FULLSTACK DEVELOPMENT
feeds/latest/ for the LatestEntries feed.
feeds/categories/ for the LatestEntriesByCategory feed.
20
21CS62 | FULLSTACK DEVELOPMENT
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.
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]
21
21CS62 | FULLSTACK DEVELOPMENT
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.
22
21CS62 | FULLSTACK DEVELOPMENT
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)
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.
23
21CS62 | FULLSTACK DEVELOPMENT
5. Example Sitemap Class:
class BlogSitemap(Sitemap):
changefreq = "never"
priority = 0.5
def items(self):
return Entry.objects.filter(is_draft=False)
return obj.pub_date
6. Convenience Classes:
FlatPageSitemap: For flatpages defined for the current site.
GenericSitemap: Works with generic views.
24
21CS62 | FULLSTACK DEVELOPMENT
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}),
)
25
21CS62 | FULLSTACK DEVELOPMENT
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
26
21CS62 | FULLSTACK DEVELOPMENT
Cookies, Sessions
Introduction to Cookies:
Example:
Browser requests a page from Google:
GET / HTTP/1.1
Host: google.com
27
21CS62 | FULLSTACK DEVELOPMENT
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.")
28
21CS62 | FULLSTACK DEVELOPMENT
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.
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.
29
21CS62 | FULLSTACK DEVELOPMENT
Django’s Session Framework
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',
...
]
30
21CS62 | FULLSTACK DEVELOPMENT
Getting a session value:
fav_color = request.session["fav_color"]
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!')
31
21CS62 | FULLSTACK DEVELOPMENT
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()
32
21CS62 | FULLSTACK DEVELOPMENT
Sessions Outside of Views
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
33
21CS62 | FULLSTACK DEVELOPMENT
Session Settings
34
21CS62 | FULLSTACK DEVELOPMENT
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.
35
21CS62 | FULLSTACK DEVELOPMENT
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()
36
21CS62 | FULLSTACK DEVELOPMENT
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.