FSD Module 04
FSD Module 04
FSD Module 04
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.
Used by creating configuration dictionaries in URLconf.
Example: Static "About" Page Examples include direct_to_template for rendering static templates.
Other generic views include list views, detail views, and more.
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.
21CS62 | FULLSTACK DEVELOPMENT
Advanced Example: Dynamic Static 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.
21CS62 | FULLSTACK DEVELOPMENT
4.2 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']
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.
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.
21CS62 | FULLSTACK DEVELOPMENT
Example:
publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
'template_object_name': 'publisher',
urlpatterns = patterns('',
)
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}
}
21CS62 | FULLSTACK DEVELOPMENT
Viewing Subsets of Objects
Example
apress_books = {
'template_name': 'books/apress_list.html'
urlpatterns = patterns('',
)
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),
)
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),
# ...
)
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
21CS62 | FULLSTACK DEVELOPMENT
4.4 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.
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.
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).
21CS62 | FULLSTACK DEVELOPMENT
4.5 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
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
1. PDF Format:
• PDF (Portable Document Format) is used for printable documents with precise
formatting.
def hello_pdf(request):
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'
p = canvas.Canvas(response)
p.drawString(100, 100, "Hello world.")
p.showPage()
p.save()
return response
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:
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]
• 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.
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.
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.
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}),
)
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
21CS62 | FULLSTACK DEVELOPMENT
4.8 Cookies, Sessions
Introduction to Cookies:
• Example:
• Browser requests a page from Google:
GET / HTTP/1.1
Host: google.com
• 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.")
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.
• 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',
...
]
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!')
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()
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