0% found this document useful (0 votes)
16 views23 pages

M4 1

Module 4

Uploaded by

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

M4 1

Module 4

Uploaded by

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

MODULE 4

Using Generic Views, Generic Views of Objects, Extending Generic Views


of objects, Extending Generic Views. MIME Types, Generating Non-
HTML contents like CSV and PDF, Syndication Feed Framework, Sitemap
framework, Cookies, Sessions, Users and Authentication.
Using Generic Views, Generic Views of
Objects
• Django’s generic views provide a shortcut for common tasks, like
displaying a list of objects or showing detailed views of a single
object.
• Generic views simplify the process by handling common logic for
these operations, allowing you to focus on the unique parts of your
application.
Generic View Overview
• Django provides several types of generic views, including:
• ListView: For displaying a list of objects.
• DetailView: For displaying a single object in detail.
• CreateView: For creating a new object.
• UpdateView: For updating an existing object.
• DeleteView: For deleting an object.
Using ListView to Display Lists of
Objects
ListView is used to display a list of objects, typically from a
model.

• Using DetailView to Display a Single Object


• Using CreateView for Object Creation
• Using UpdateView for Object Updating
• Using DeleteView for Object Deletion
Using
# views.py
ListView to Display Lists of Objects
from django.views.generic import ListView
from .models import MyModel
class MyModelListView(ListView):
model = MyModel
template_name = 'myapp/mymodel_list.html' # Specify your template
context_object_name = 'objects' # Default is 'object_list'
paginate_by = 10 # Optional pagination
• In urls.py, link the view to a URL:
from django.urls import path
from .views import MyModelListView

urlpatterns = [
path('mymodel/', MyModelListView.as_view(), name='mymodel_list'),
]
Using DetailView to Display a Single Object
# views.py
from django.views.generic import DetailView
from .models import MyModel

class MyModelDetailView(DetailView):
model = MyModel
template_name = 'myapp/mymodel_detail.html' # Specify your template
context_object_name = 'object' # Default is 'object'
• In urls.py, connect it with a URL and specify the primary key or slug:
from django.urls import path
from .views import MyModelDetailView

urlpatterns = [
path('mymodel/<int:pk>/', MyModelDetailView.as_view(), name='mymodel_detail'),
]
Using CreateView for Object Creation
• CreateView is used for displaying a form to create a new object and save it to the database
upon submission.
# views.py
from django.views.generic import CreateView
from .models import MyModel
from .forms import MyModelForm # Custom form (optional)

class MyModelCreateView(CreateView):
model = MyModel
form_class = MyModelForm # Or use 'fields = ['field1', 'field2']'
template_name = 'myapp/mymodel_form.html'
success_url = '/mymodel/' # Redirect after a successful save
url pattern:
urlpatterns = [
path('mymodel/add/', MyModelCreateView.as_view(), name='mymodel_add'),
]
Using UpdateView for Object Updating

• UpdateView is similar to CreateView but used for editing an existing object.

# views.py
from django.views.generic import UpdateView
class MyModelUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
template_name = 'myapp/mymodel_form.html'
success_url = '/mymodel/’
url pattern:
urlpatterns = [ path('mymodel/<int:pk>/edit/',
MyModelUpdateView.as_view(), name='mymodel_edit'), ]
Using DeleteView for Object Deletion

• DeleteView displays a confirmation page and deletes an object upon


confirmation.
• # views.py
from django.views.generic import DeleteView
class MyModelDeleteView(DeleteView):
model = MyModel
template_name = 'myapp/mymodel_confirm_delete.html'
success_url = '/mymodel/’
• url pattern:
urlpatterns = [ path('mymodel/<int:pk>/delete/',
MyModelDeleteView.as_view(), name='mymodel_delete'), ]
Cont.
Benefits of Using Generic Views
 Reduced Boilerplate: Generic views handle common logic,
so you write less code.
 Consistency: All views share a consistent interface, making
them easier to manage.
 Customizable: Override methods or templates to tailor the
views to your needs.
MIME TYPES
• MIME types (Multipurpose Internet Mail Extensions) in Django refer to
the content types used to inform browsers or clients about the type of
data being returned in a response.
• They play a critical role in serving files, ensuring the client handles the
response correctly.
• MIME types are typically set in the Content-Type HTTP header of a
response. Common MIME types include:
 Text formats: text/html, text/plain, text/css, application/javascript
 Images: image/png, image/jpeg, image/gif
 Applications: application/json, application/pdf
 Audio/Video: audio/mpeg, video/mp4
Generating Non-HTML contents like CSV and
PDF
• Refer word file names “Generating csv and pdf “
Syndication Feed Framework
• The Syndication Feed Framework in Django is used to generate RSS
(Really Simple Syndication) and Atom feeds.
• These feeds are typically used to deliver updates, such as blog posts,
news articles, or any type of content, to users who have subscribed
to them.
• The feed can be consumed by feed readers or aggregators.
• Django provides a built-in framework to handle syndication feeds,
which is highly customizable.
Sitemap framework
Sitemap is used to generate XML sitemaps for websites.
In Django, the sitemap framework typically involves the following steps:
1. Define a Sitemap Class: Create a class that specifies the logic to retrieve the
items (URLs) for the sitemap and their metadata (e.g., last modification date,
change frequency, priority).
2. Register the Sitemap: Use Django's sitemaps module to map the defined class to
a URL pattern.
3. Generate the Sitemap: Django dynamically generates the XML sitemap at the
specified URL.
Cookies and Sessions
• In Django, cookies and sessions are mechanisms to store data about a
user between requests.
• They are both used for maintaining user state, but they work in
different ways.
• Cookies are small pieces of data stored on the client's browser. They
are typically used for tracking and storing user-specific information,
such as user preferences, authentication tokens, etc. Cookies are sent
with every request to the server, which allows the server to maintain
state across multiple requests.
Cont.
• To set cookies, you use the HttpResponse object's set_cookie()
method.
Setting a cookie in a view
from django.http import HttpResponse
• def set_cookie_view(request):
• response = HttpResponse("Setting a cookie")
• response.set_cookie('username', 'john_doe') # Set cookie with
name 'username' and value 'john_doe'
• return response
Cont.
To retrieve the value of a cookie, you can use request.COOKIES, which returns a
dictionary containing all cookies sent with the request.

Retrieving a cookie value:


views.py
from django.http import HttpResponse
def get_cookie_view(request):
username = request.COOKIES.get('username', 'Guest') # Default to
'Guest' if 'username' cookie does not exist
return HttpResponse(f"Hello, {username}")
Cont.
To delete a cookie, you can use the delete_cookie() method on the
response object.

views.py
from django.http import HttpResponse
def delete_cookie_view(request):
response = HttpResponse("Cookie has been deleted")
response.delete_cookie('username') # Delete the 'username' cookie
return response
Sessions
• Sessions are used to store data on the server side, while the client
side only stores a session ID in a cookie.
• Sessions are more secure than cookies because sensitive data is
stored on the server, not on the client side.
• The session ID is sent back and forth between the client and the
server using a cookie.
• Django's session framework uses signed cookies to store the session
ID on the client side.
• When the client makes a request, Django retrieves the session data
from the database using the session ID.
Comparisons
Feature Feature Feature
Stored on the client
Storage Stored on the server
(browser)
Less secure (client-side More secure (server-side
Security
storage) storage)
Can store large amounts of
Data Capacity Limited to 4 KB
data
Storing user-specific data like
Use Case Storing preferences, tracking
authentication
Set by the server, expires
Expiration Set by the server or client
after a period of inactivity
# views.py
from django.http import HttpResponse
from django.shortcuts import render

def login_view(request):
if request.method == 'POST':
# Simulate authentication
username = request.POST.get('username')
request.session['username'] = username
response = HttpResponse(f"Logged in as {username}")
response.set_cookie('username', username) # Set a cookie for future visits
return response
return render(request, 'login.html')

def logout_view(request):
request.session.flush() # Clears all session data
response = HttpResponse("You have logged out")
response.delete_cookie('username') # Delete the cookie
return response
Users and Authentication
• In Django, users and authentication are integral parts of web
development, enabling user registration, login, logout, and access
control.
• Django provides built-in views, forms, and models to simplify the
process of managing users and authentication.
Cont.
• Django provides built-in views, forms, and models for handling
authentication, user registration, and permissions.
• You can extend the default User model to include additional fields
like bio, date_of_birth, etc.
• Use session-based authentication to maintain user login state across
requests.
• Implement access control using decorators like login_required and
user_passes_test.

You might also like