Module-04 FSD
Module-04 FSD
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.
Page 1
Full Stack Development
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:
1. Generic Views:
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.
Page 3
Full Stack Development
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']
Page 4
Full Stack 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.
Page 5
Full Stack Development
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.
Page 6
Full Stack Development
Example:
publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
'template_object_name': 'publisher',
urlpatterns = patterns('',
Page 7
Full Stack 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}
}
Page 8
Full Stack Development
Example
apress_books = {
'template_name': 'books/apress_list.html'
urlpatterns = patterns('',
Page 9
Full Stack Development
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),
Page 10
Full Stack Development
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),
# ...
Page 11
Full Stack Development
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
Page 12
Full Stack 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.
Page 13
Full Stack 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.
Page 14
Full Stack 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).
Page 15
Full Stack Development
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
Page 16
Full Stack Development
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
Page 17
Full Stack Development
1. PDF Format:
PDF (Portable Document Format) is used for printable documents with
precise formatting.
Page 18
Full Stack Development
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:
Page 19
Full Stack 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]
Page 20
Full Stack 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.
Page 21
Full Stack 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.
Page 22
Full Stack Development
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.
Page 23
Full Stack Development
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}),
)
Page 24
Full Stack 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
Page 25
Full Stack Development
Cookies, Sessions
Introduction to Cookies:
Example:
Browser requests a page from Google:
GET / HTTP/1.1
Host: google.com
Page 26
Full Stack Development
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.")
Page 27
Full Stack Development
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.
Page 28
Full Stack Development
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',
...
]
Page 29
Full Stack Development
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!')
Page 30
Full Stack 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()
Page 31
Full Stack Development
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
Page 32
Full Stack Development
Session Settings
Page 33
Full Stack Development
Page 34
Full Stack Development
Page 35
Full Stack Development
Page 36