M4 1
M4 1
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
# 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
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.