[go: up one dir, main page]

0% found this document useful (0 votes)
11 views14 pages

FSD Module 4

This is the trial documents

Uploaded by

Prakash Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views14 pages

FSD Module 4

This is the trial documents

Uploaded by

Prakash Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Sri Sai Vidya Vikas Shikshana Samithi ®

SAI VIDYA INSTITUTE OF TECHNOLOGY


Approved by AICTE, New Delhi, Affiliated to VTU, Recognized by Govt. of Karnataka
Accredited by NBA
RAJANUKUNTE, BENGALURU 560 064, KARNATAKA
Phone: 080-28468191/96/97/98 ,Email: info@saividya.ac.in, URLwww.saividya.ac.in

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CSE)

Module-4: Generic Views and Django State Persistence

4.1 Overview of Django's Generic Views

Generic views in Django are a powerful tool that allows developers to create views for common tasks with minimal code.
They provide a high-level abstraction for common web development patterns, such as displaying a list of objects, displaying
a detail page for a single object, handling form submissions, etc. By using generic views, you can quickly build and maintain
standard views without having to write repetitive boilerplate code.

Types of Generic Views

1. Simple Tasks

Rendering a Template:

# views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
template_name = 'about.html'

# urls.py
from django.urls import path
from .views import AboutView

urlpatterns = [
path('about/', AboutView.as_view(), name='about'),
]

Redirecting to a Different Page:

You can use RedirectView to redirect to a different URL.

# views.py
from django.views.generic import RedirectView

class HomeRedirectView(RedirectView):
url = '/home/'

# urls.py
from django.urls import path
from .views import HomeRedirectView

urlpatterns = [

Deepika G, Dept of CSE, SVIT Page 1


path('', HomeRedirectView.as_view(), name='home-redirect'),
]

2. List and Detail Pages

# views.py
from django.views.generic import ListView
from .models import Event

class EventListView(ListView):
model = Event
template_name = 'event_list.html'
context_object_name = 'events'

# urls.py
from django.urls import path
from .views import EventListView

urlpatterns = [
path('events/', EventListView.as_view(), name='event-list'),
]

DetailView Example:

# views.py
from django.views.generic import DetailView
from .models import Event

class EventDetailView(DetailView):
model = Event
template_name = 'event_detail.html'
context_object_name = 'event'

# urls.py
from django.urls import path
from .views import EventDetailView

urlpatterns = [
path('events/<int:pk>/', EventDetailView.as_view(), name='event-detail'),
]

3. Date-Based Objects

Date-based views allow you to present objects organized by dates.

ArchiveIndexView Example:

# views.py
from django.views.generic.dates import ArchiveIndexView
from .models import Article

class ArticleArchiveIndexView(ArchiveIndexView):

Deepika G, Dept of CSE, SVIT Page 2


model = Article
date_field = 'publication_date'
template_name = 'article_archive.html'

# urls.py
from django.urls import path
from .views import ArticleArchiveIndexView

urlpatterns = [
path('articles/archive/', ArticleArchiveIndexView.as_view(), name='article-archive'),
]

4. CRUD Operations

# views.py
from django.views.generic import CreateView
from .models import Event

class EventCreateView(CreateView):
model = Event
template_name = 'event_form.html'
fields = ['name', 'location', 'date']
success_url = '/events/'

# urls.py
from django.urls import path
from .views import EventCreateView

urlpatterns = [
path('events/create/', EventCreateView.as_view(), name='event-create'),
]

UpdateView Example:

# views.py
from django.views.generic import UpdateView
from .models import Event

class EventUpdateView(UpdateView):
model = Event
template_name = 'event_form.html'
fields = ['name', 'location', 'date']
success_url = '/events/'

# urls.py
from django.urls import path
from .views import EventUpdateView

urlpatterns = [
path('events/<int:pk>/update/', EventUpdateView.as_view(), name='event-update'),
]

Deepika G, Dept of CSE, SVIT Page 3


DeleteView Example:

# views.py
from django.views.generic import DeleteView
from .models import Event

class EventDeleteView(DeleteView):
model = Event
template_name = 'event_confirm_delete.html'
success_url = '/events/'
# urls.py
from django.urls import path
from .views import EventDeleteView

urlpatterns = [
path('events/<int:pk>/delete/', EventDeleteView.as_view(), name='event-delete'),
]

4.1 Using Generic Views

In Django, generic views provide a way to handle common patterns in web development with minimal code. The
example provided demonstrates how to configure a generic view in a URLconf file to render a static "about" page
using the direct_to_template generic view.

URLconf File

The URLconf file in Django is where URL patterns for the application are defined. It maps URLs to views. In the
example, the URLconf file is setting up a route for the "about" page.

Example for a static "about" page:

from django.conf.urls.defaults import *


from django.views.generic.simple import direct_to_template

urlpatterns = patterns('', ('^about/$', direct_to_template, {'template': 'about.html'}))

 from django.conf.urls.defaults import *: This import statement includes all the default URL configuration
tools provided by Django.
 from django.views.generic.simple import direct_to_template: This imports the direct_to_template
generic view, which is used to render a specified template without needing to write a separate view
function.
 patterns(''): This function is used to define URL patterns. The first argument is a prefix for the views, which
is an empty string in this case.
 '^about/$': This is a regular expression that matches the URL path. The caret (^) indicates the start of the
string, and the dollar sign ($) indicates the end of the string. So, this pattern matches the URL /about/.
 direct_to_template: This is the view function that will be called when the URL pattern is matched. In this
case, it's the direct_to_template generic view.
 {'template': 'about.html'}: This is a dictionary of keyword arguments that will be passed to the
direct_to_template view. Here, it specifies the template name 'about.html'.

Deepika G, Dept of CSE, SVIT Page 4


4.2 Generic Views of Objects

Django's generic views provide a streamlined way to present database content in your web application. By using
these views, you can quickly create views that handle common tasks like displaying lists of objects or detail pages
for individual objects.

The below example demonstrates how to create a "publisher list" view using a generic view:

Example:

from django.conf.urls.defaults import *


from django.views.generic import list_detail
from mysite.books.models import Publisher

publisher_info = {
"queryset" : Publisher.objects.all(),
}

urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)

 from django.urls import path: Imports the path function for defining URL patterns.
 from django.views.generic import ListView: Imports the ListView generic view.
 from mysite.books.models import Publisher: Imports the Publisher model.
 path('publishers/', ListView.as_view(model=Publisher)): Defines a URL pattern for /publishers/ and uses
ListView to display a list of Publisher objects.

4.3 Customizing and Extending Generic Views

1. Friendly Template Contexts: Change the name of the context variable to be more descriptive.

publisher_info = {
"queryset" : Publisher.objects.all(),
"template_object_name" : "publisher",
}

2. Adding Extra Context: Pass additional information to the template using extra_context.

publisher_info = {
"queryset" : Publisher.objects.all(),
"extra_context" : {"publisher_list" : Publisher.objects.all}
}

3. Viewing Subsets of Objects: Filter objects displayed by the view using the queryset key.

apress_books = {
"queryset": Book.objects.filter(publisher__name="Apress Publishing"),
"template_name" : "books/apress_list.html"

Deepika G, Dept of CSE, SVIT Page 5


}

4. Complex Filtering with Wrapper Functions: Use wrapper functions to filter objects based on URL
parameters.

from django.http import Http404


from django.views.generic import list_detail
from mysite.books.models import Book, Publisher

def books_by_publisher(request, name):


try:
publisher = Publisher.objects.get(name__iexact=name)
except Publisher.DoesNotExist:
raise Http404

return list_detail.object_list(
request,
queryset = Book.objects.filter(publisher=publisher),
template_name = "books/books_by_publisher.html",
template_object_name = "books",
extra_context = {"publisher" : publisher}
)

5. Performing Extra Work: Execute additional tasks before or after the generic view.

from mysite.books.models import Author


from django.views.generic import list_detail
from django.shortcuts import get_object_or_404

def author_detail(request, author_id):


author = get_object_or_404(Author, pk=author_id)
author.last_accessed = datetime.datetime.now()
author.save()

return list_detail.object_detail(
request,
queryset = Author.objects.all(),
object_id = author_id,
)

4.4 MIME Types

 MIME, which stands for Multipurpose Internet Mail Extensions, is a standard that indicates the nature and
format of a document or file.
 It allows the exchange of different kinds of data files on the internet, including text, images, audio, video,
and application programs.
 The MIME type is a way of specifying the type of content being dealt with, allowing the browser or email
client to handle the content appropriately.

Deepika G, Dept of CSE, SVIT Page 6


4.5 MIME Types and Their Usage

MIME types are used to inform the browser about the type of content being returned by a Django view

1. image/png

from django.http import HttpResponse

def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
return HttpResponse(image_data, mimetype="image/png")

 Type: image/png
 Description: This MIME type tells the browser that the content being returned is a PNG image. When the
browser receives this response, it will display the image correctly.

2. text/csv

import csv
from django.http import HttpResponse

UNRULY_PASSENGERS = [146, 184, 235, 200, 226, 251, 299, 273, 281, 304, 203]

def unruly_passengers_csv(request):
response = HttpResponse(mimetype='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, 2006), UNRULY_PASSENGERS):
writer.writerow([year, num])

return response

 Type: text/csv
 Description: This MIME type indicates that the content is a CSV file. The Content-Disposition header
suggests that the browser should prompt the user to download the file as unruly.csv.

3. application/pdf

from reportlab.pdfgen import canvas


from django.http import HttpResponse

def hello_pdf(request):
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'

p = canvas.Canvas(response)

Deepika G, Dept of CSE, SVIT Page 7


p.drawString(100, 100, "Hello world.")
p.showPage()
p.save()
return response

 Type: application/pdf
 Description: This MIME type indicates that the content is a PDF document. The Content-Disposition header
again suggests that the browser should prompt the user to download the file as hello.pdf.

4.6 Non-HTML contents CSV and PDF

Generating CSV and PDF files dynamically using Django and Python involves leveraging Python's built-in libraries
and Django's HttpResponse object to deliver content directly to users or to store it for later use. Here’s a concise
breakdown for each format:

Generating CSV Files

CSV (Comma-Separated Values) files are straightforward to generate using Python's csv module along with
Django's HttpResponse object. Here's a step-by-step approach:

1. Setup Your Data: Prepare your data in a list or retrieve it from a database.

UNRULY_PASSENGERS = [
(1995, 146),
(1996, 184),
(1997, 235),
# Add more years and passenger data as needed
]

2. Create a Django View Function: Define a view function that creates a CSV file and serves it as a download.

import csv
from django.http import HttpResponse

def unruly_passengers_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="unruly_passengers.csv"'

writer = csv.writer(response)
writer.writerow(['Year', 'Unruly Airline Passengers'])

for year, passengers in UNRULY_PASSENGERS:


writer.writerow([year, passengers])

return response

 HttpResponse: Initializes an HTTP response object.


 Content-Type: Specifies the response content type as CSV (text/csv).
 Content-Disposition: Forces the browser to treat the response as a file download.
 csv.writer: Writes rows to the CSV file using the response object.

Generating PDF Files

Deepika G, Dept of CSE, SVIT Page 8


PDF (Portable Document Format) files require the ReportLab library, which integrates well with Django. Here's a
basic setup:

1. Install ReportLab: Install the library using pip if not already installed.

pip install reportlab

2. Create a Django View Function: Define a view function that generates a PDF file and serves it as a
download.

from io import BytesIO


from reportlab.pdfgen import canvas
from django.http import HttpResponse

def hello_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="hello.pdf"'

buffer = BytesIO()
p = canvas.Canvas(buffer)

p.drawString(100, 100, "Hello, World!")

p.showPage()
p.save()

pdf = buffer.getvalue()
buffer.close()

response.write(pdf)
return response

 HttpResponse: Initializes an HTTP response object.


 Content-Type: Specifies the response content type as PDF (application/pdf).
 Content-Disposition: Forces the browser to treat the response as a file download.
 canvas.Canvas: Creates a canvas object to draw on.
 showPage() and save(): Finalizes the PDF document.

Integration with Django

 Ensure your view functions are correctly mapped to URLs in your Django application's urls.py.
 Use these functions to dynamically generate CSV or PDF files based on user requests or application logic.
 Handle errors and edge cases, such as missing data or unexpected input, gracefully in your view functions.

4.7 Setting Up Syndication Feeds in Django

Setting up syndication feeds in Django involves several steps.

1. Installation and Configuration

Ensure Django is installed and configured in your project. Syndication feeds are part of Django’s built-in
functionality and require no separate installation beyond Django itself.

2. URL Configuration

Define URL patterns in your Django project's URLconf to handle syndication feeds:
Deepika G, Dept of CSE, SVIT Page 9
from django.conf.urls import patterns, url
from myapp.feeds import LatestEntriesFeed

urlpatterns = [
url(r'^feeds/latest/$', LatestEntriesFeed(), name='latest_entries_feed'),
# Add more URL patterns for other feeds if needed
]

3. Creating Feed Classes

Create Python classes that define your feeds. These classes will subclass django.contrib.syndication.views.Feed.
Each feed class represents a different type of syndication feed (RSS or Atom).

from django.contrib.syndication.views import Feed


from myapp.models import Entry

class LatestEntriesFeed(Feed):
title = "Latest Entries"
link = "/latest/feed/"
description = "Latest entries from my site"

def items(self):
return Entry.objects.order_by('-pub_date')[:10]

def item_title(self, item):


return item.title

def item_description(self, item):


return item.description

def item_link(self, item):


return item.get_absolute_url()

4. Template Setup (Optional)

Create templates for each feed item to customize how they appear in the feed. Django looks for templates named
<feed_slug>_title.html and <feed_slug>_description.html by default.

5. URLconf Integration

Integrate your feed classes into the URL configuration:

from django.conf.urls import url


from django.contrib.syndication.views import Feed
from myapp.feeds import LatestEntriesFeed

urlpatterns = [
# Other URL patterns
url(r'^feeds/latest/$', LatestEntriesFeed(), name='latest_entries_feed'),
]

Deepika G, Dept of CSE, SVIT Page 10


6. Testing Feeds

Run your Django development server and navigate to /feeds/latest/ (or your defined URL) to test if the feed is
rendering correctly in your browser.

7. Customizing Feed Types

You can customize feed types by setting the feed_type attribute of your feed class to Atom1Feed or another feed
type available in Django’s feedgenerator.

8. Additional Feed Options

 Enclosures: Specify media enclosures (e.g., audio or video files) using item_enclosure_url,
item_enclosure_length, and item_enclosure_mime_type methods in your feed class.
 Language: Feeds automatically include language tags based on your LANGUAGE_CODE setting.
 Multiple Feeds: You can create multiple feeds by defining additional feed classes and adding them to the
urlpatterns and feed_dict.

9. Deployment and Monitoring

Deploy your Django project to a production environment and monitor feed updates. You can use tools like Django
management commands or scheduled tasks (cron jobs) to manage feed updates and ensure they reflect the latest
content.

4.8 Sitemap Framework

The sitemap framework in Django automates the creation of XML sitemap files, which are used by search engines
to understand the structure of your website and prioritize crawling of its pages. Here’s a breakdown of how the
Django sitemap framework works and its key components:

Installation and Setup

1. Installation: Add 'django.contrib.sitemaps' to your INSTALLED_APPS setting in Django. Ensure that


'django.template.loaders.app_directories.load_template_source' is in your TEMPLATE_LOADERS setting
(usually it's there by default).
2. Configuration: You need to have the sites framework installed ('django.contrib.sites' in INSTALLED_APPS)
since sitemaps are associated with specific sites within your Django project.

Creating a Sitemap

To create a sitemap for your Django project, you typically define a subclass of django.contrib.sitemaps.Sitemap.
This class defines the structure and content of the URLs that should be included in the sitemap.

Example: BlogSitemap
from django.contrib.sitemaps import Sitemap
from mysite.blog.models import Entry

class BlogSitemap(Sitemap):
changefreq = "never" # How often the page changes
priority = 0.5 # Priority of the page (0.0 to 1.0)

def items(self):
return Entry.objects.filter(is_draft=False)

Deepika G, Dept of CSE, SVIT Page 11


def lastmod(self, obj):
return obj.pub_date # Date of last modification for the object

# Optional: Define location() method if get_absolute_url() is not used


# def location(self, obj):
# return obj.get_absolute_url()

Integration with URLconf

In your Django urls.py, you map the sitemap view to a URL:

from django.urls import path


from django.contrib.sitemaps.views import sitemap
from mysite.sitemaps import BlogSitemap

sitemaps = {
'blog': BlogSitemap,
}

urlpatterns = [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps}),
]

Sitemap Index

For larger sites, you can create a sitemap index that references multiple sitemap files. This is done by setting up
additional URL patterns in urls.py:

from django.contrib.sitemaps.views import index

urlpatterns = [
path('sitemap.xml', index, {'sitemaps': sitemaps}),
path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}),
]

Pinging Search Engines

Django provides a utility function django.contrib.sitemaps.ping_google() to notify Google about changes to your
sitemap. This can be automated via cron jobs or called manually to ensure search engines are aware of updates.

4.9 Cookies and Sessions

Cookies and sessions are both mechanisms used in web development to maintain stateful information between
HTTP requests, but they serve different purposes and have distinct characteristics:

Cookies

1. Definition: Cookies are small pieces of data stored by the browser on behalf of a web server. They are sent
by the browser with every request to the server that set them.
2. Purpose: Cookies are primarily used for session management, personalization, tracking user behavior, and
maintaining state between HTTP requests.
3. Implementation:

Deepika G, Dept of CSE, SVIT Page 12


Reading Cookies: In Django, cookies are accessible through the request.COOKIES dictionary. This
o
allows you to read cookies sent by the client.
o Setting Cookies: Cookies are set using the set_cookie() method on HttpResponse objects. This
method allows you to specify attributes like max_age, expires, path, domain, and secure.
4. Characteristics:
o Persistence: Cookies can be persistent (remain on the client after the browser is closed) or session-
based (deleted when the browser session ends).
o Security: Cookies are vulnerable to attacks such as interception and modification, especially if
transmitted over unsecured HTTP connections.
o Size Limitation: Browsers impose limits on the size and number of cookies that can be stored for a
particular domain.

Sessions

1. Definition: Sessions are server-side objects that store client-specific data to be used across multiple pages
or visits by the same user.
2. Purpose: Sessions are typically used for user authentication, storing shopping cart information, and
maintaining user-specific settings.
3. Implementation:
o In Django, session handling is abstracted and can be configured using different backends
(django.contrib.sessions.backends).
o Session data is stored on the server, and the client typically only stores a session ID in a cookie.
4. Characteristics:
o Storage: Session data is stored on the server, ensuring it's not exposed to the client and thus more
secure compared to cookies.
o Management: Sessions can be managed to expire after a certain time or when the user logs out.
o Security: Session data is not directly accessible or modifiable by the client, providing better security
for sensitive information.

Comparison and Best Practices

 Sensitive Information: Never store sensitive information (like passwords or authentication tokens) in
cookies due to security risks. Use sessions for such data.
 Persistence: Choose cookies for non-sensitive, user-specific data that needs to persist across sessions. Use
sessions for critical data that requires server-side control and security.
 Performance: Cookies are lighter and faster to manage than sessions because they involve minimal server-
side processing.

4.10 Users and Authentication.

In Django's authentication system, users and authentication are handled through a comprehensive set of tools
designed to manage user accounts, permissions, and sessions effectively. Here’s a breakdown of key concepts and
how Django implements them:

Users

1. Definition: Users are individuals registered with your website. Each user has a unique identity and
associated attributes stored in the database.
2. Attributes: Django's User model includes fields such as username, first_name, last_name, email, password,
is_staff, is_active, is_superuser, last_login, and date_joined.
o username: Required, alphanumeric identifier.
Deepika G, Dept of CSE, SVIT Page 13
opassword: Stored securely as a hash.
o is_staff: Determines access to Django's admin interface.
o is_active: Specifies if the user can log in.
o is_superuser: Grants all permissions without explicit assignment.
3. Methods: Django provides methods like is_authenticated(), is_anonymous(), get_full_name(),
set_password(), check_password(), get_group_permissions(), get_all_permissions(), and more. These
methods facilitate user management and permission checking.

Authentication

1. Verification: Authentication in Django involves verifying a user's identity using credentials (typically
username and password).
o authenticate(): Checks if provided credentials are valid against the database.
o login(): Logs in a user by storing their ID in the session.
2. Logging In/Out: Django provides built-in functions and views to handle user authentication:
o login(request, user): Logs a user in after successful authentication.
o logout(request): Logs a user out by removing their ID from the session.
3. Integration: Authentication in Django is integrated with its session framework. Once authenticated, the
request.user object represents the current user, providing access to user-specific data and permissions.

Authorization

1. Permissions: Django uses permissions to authorize users to perform specific actions or access certain parts
of the application.
o Permission Checks: Methods like has_perm() and decorators like permission_required() allow
developers to enforce access control based on user permissions.

Sessions

1. Purpose: Sessions store user-specific data on the server-side across multiple requests. They are essential
for maintaining user login states and managing persistent data during a user's interaction with the site.
2. Usage: Django integrates session management with authentication seamlessly, ensuring that once a user is
authenticated, their session can persist until they log out or the session expires.

Django's authentication system provides robust tools for managing user identities, securing sensitive information,
and controlling access to application features based on user roles and permissions. Understanding these concepts
and leveraging Django’s built-in functionalities can streamline development while ensuring security and user
management best practices are followed.

Deepika G, Dept of CSE, SVIT Page 14

You might also like