Managing Cookies, Sessions, and Custom Pagination in Django
Cookie Fundamentals
Why Cookies Exist
HTTP is a stateless protocol. Each request is independent, meaning the server treats every interaction as a brand-new encounter without memory of previous requests. However, web applications often need to "remember" user data across multiple requests. Cookies were introduced to solve this problem by allowing state to be maintained.
Definition
A cookie is a small piece of data stored on the client's browser as a key-value pair. When the browser sends subsequent requests to the same server, it automatically includes these cookies, allowing the server to identify the user or retrieve preferences.
Mechanism
The server generates the cookie content and sends it to the browser via a response header. The browser stores it locally. On future visits, the browser attaches the cookie to the request header, enabling the server to identify the client.
Working with Cookies in Django
Reading Cookies
# Access a standard cookie
request.COOKIES.get('key')
# Access a signed cookie (tamper-resistant)
request.get_signed_cookie(key='key', default=None, salt='mysalt', max_age=3600)
Parameters:
default: Value returned if the key doesn't exist.salt: Used to hash the cookie value for verification.max_age: Number of seconds the cookie is valid.
Writing Cookies
response = HttpResponse("Hello")
# or response = render(request, 'template.html')
# Standard cookie
response.set_cookie('username', 'john_doe')
# Signed cookie
response.set_signed_cookie('session_token', 'abc123', salt='mysalt')
Parameters:
key: The name of the cookie.value: The string value to store.max_age: Active duration in seconds.expires: Specificdatetimeobject for expiration (useful for IE).path: URL path where the cookie is valid (default/makes it site-wide).domain: Domain scope for the cookie.secure: Boolean indicating if the cookie should only be sent over HTTPS.httponly: Boolean preventing JavaScript access to the cookie (mitigates XSS).
Removing Cookies
def user_logout(request):
redirect_response = redirect('/signin/')
# Remove the specific cookie
redirect_response.delete_cookie('username')
return redirect_response
Cookie-Based Auth Example
from functools import wraps
# Decorator to protect views
def require_login(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
target_url = request.get_full_path()
# Verify signed cookie
if request.get_signed_cookie('is_authenticated', salt='secretkey', default=False) == 'true':
return view_func(request, *args, **kwargs)
return redirect(f'/signin/?next={target_url}')
return wrapper
def signin_view(request):
if request.method == 'POST':
user = request.POST.get('user')
passcode = request.POST.get('passcode')
if user == 'admin' and passcode == 'secretpass':
destination = request.GET.get('next')
http_response = redirect(destination or '/dashboard/')
# Set a signed cookie to mark the user as logged in
http_response.set_signed_cookie('is_authenticated', 'true', salt='secretkey')
return http_response
return render(request, 'signin.html')
Session Management
The Need for Sessions
While cookies are useful, they have limitations: they are stored client-side (insecure) and have size limits (approx 4KB). Sessions address this by storing sensitive data on the server while keeping only a unique Session ID in the client's cookie. This ID acts as a key to retrieve the server-side data.
Django Session Operations
# Accessing data
session_val = request.session['key']
user_info = request.session.get('user_id', None)
# Modifying data
request.session['key'] = 'value'
request.session.setdefault('key', 'default_value') # Set only if not exists
del request.session['key']
# Metadata
session_key = request.session.session_key
request.session.clear_expired() # Clean up old sessions
# Deletion
request.session.delete() # Remove session data (keep cookie)
request.session.flush() # Remove session data AND cookie
# Expiry
request.session.set_expiry(300) # Expires in 300 seconds
request.session.set_expiry(None) # Default behavior
request.session.set_expiry(0) # Expires when browser closes
Session-Based Authantication
from functools import wraps
def check_auth(view_func):
@wraps(view_func)
def inner(request, *args, **kwargs):
if request.session.get('logged_in_user'):
return view_func(request, *args, **kwargs)
return redirect(f'/login/?next={request.get_full_path()}')
return inner
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'john' and password == 'doe123':
request.session['logged_in_user'] = username
next_page = request.GET.get('next')
return redirect(next_page or '/profile/')
return render(request, 'login.html')
@check_auth
def profile_view(request):
current_user = request.session.get('logged_in_user')
return render(request, 'profile.html', {'user': current_user})
@check_auth
def logout_view(request):
request.session.flush()
return redirect('/login/')
Session Configuration
Djengo supports multiple backends for storing session data. Configure them in settings.py:
- Database (Default)
SESSION_ENGINE = 'django.contrib.sessions.backends.db' - Cache
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' - File-Based
SESSION_ENGINE = 'django.contrib.sessions.backends.file' SESSION_FILE_PATH = '/tmp/django_sessions' # Optional - Cached Database
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' - Signed Cookies (Data stored in cookie, not server)
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
Common Settings:
SESSION_COOKIE_NAME = 'sessionid'SESSION_COOKIE_AGE = 1209600(2 weeks)SESSION_EXPIRE_AT_BROWSER_CLOSE = FalseSESSION_SAVE_EVERY_REQUEST = False
Using Decorators in CBV
When using Class-Based Views, decorators must be adapted:
from django.utils.decorators import method_decorator
from django.views import View
@method_decorator(check_auth, name='dispatch') # Apply to dispatch method
class ProfileView(View):
def get(self, request):
# ... logic here
return render(request, 'profile.html')
Alternatively, decoarte the dispatch method directly:
class ProfileView(View):
@method_decorator(check_auth)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
Note on CSRF: CSRF decorators (csrf_exempt, csrf_protect) must be applied to the dispatch method or the class using name='dispatch'.
Custom Pagination Logic
Implementation
def display_items(request):
item_list = [{"id": i, "title": f"Item {i}"} for i in range(1, 302)]
try:
page_num = int(request.GET.get("page", 1))
except ValueError:
page_num = 1
items_per_page = 10
total_items = len(item_list)
# Calculate total pages
total_pages = (total_items + items_per_page - 1) // items_per_page
# Calculate visible page range
visible_range = 11
half_range = visible_range // 2
start_page = max(1, page_num - half_range)
end_page = min(total_pages, page_num + half_range)
# Adjust if at the start or end
if page_num <= half_range:
end_page = min(visible_range, total_pages)
elif page_num + half_range >= total_pages:
start_page = max(1, total_pages - visible_range + 1)
# Slice data for current page
start_idx = (page_num - 1) * items_per_page
end_idx = start_idx + items_per_page
current_items = item_list[start_idx:end_idx]
# Build HTML for pagination controls
pagination_tags = []
# First/Last
pagination_tags.append(f'<li><a href="?page=1">First</a></li>')
# Previous
if page_num > 1:
pagination_tags.append(f'<li><a href="?page={page_num-1}">Prev</a></li>')
# Page numbers
for p in range(start_page, end_page + 1):
if p == page_num:
pagination_tags.append(f'<li class="active"><a href="?page={p}">{p}</a></li>')
else:
pagination_tags.append(f'<li><a href="?page={p}">{p}</a></li>')
# Next
if page_num < total_pages:
pagination_tags.append(f'<li><a href="?page={page_num+1}">Next</a></li>')
pagination_tags.append(f'<li><a href="?page={total_pages}">Last</a></li>')
page_nav_html = "".join(pagination_tags)
return render(request, 'items.html', {'items': current_items, 'pages': page_nav_html})
Reusable Pagination Class
class PaginatorHelper:
def __init__(self, current_page, item_count, url, limit=10, display_pages=11):
try:
self.page = int(current_page)
except (TypeError, ValueError):
self.page = 1
self.count = item_count
self.url = url
self.limit = limit
self.display = display_pages
# Total pages calculation
self.total_pages = (item_count + limit - 1) // limit
self.half = display_pages // 2
@property
def offset_start(self):
return (self.page - 1) * self.limit
@property
def offset_end(self):
return self.page * self.limit
def render_nav(self):
nav_list = []
# Calculate range
start = max(1, self.page - self.half)
end = min(self.total_pages, self.page + self.half)
if self.page <= self.half:
end = min(self.display, self.total_pages)
elif self.page + self.half >= self.total_pages:
start = max(1, self.total_pages - self.display + 1)
# Build links
nav_list.append(f'<a href="{self.url}?page=1">First</a>')
if self.page > 1:
nav_list.append(f'<a href="{self.url}?page={self.page-1}">Back</a>')
for num in range(start, end + 1):
if num == self.page:
nav_list.append(f'<strong>{num}</strong>')
else:
nav_list.append(f'<a href="{self.url}?page={num}">{num}</a>')
if self.page < self.total_pages:
nav_list.append(f'<a href="{self.url}?page={self.page+1}">Forward</a>')
nav_list.append(f'<a href="{self.url}?page={self.total_pages}">Last</a>')
return " | ".join(nav_list)
Django's Built-in Paginator
View Logic
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def listing_view(request):
record_list = list(range(1, 1000))
page_size = 15
paginator = Paginator(record_list, page_size)
page_number = request.GET.get('p')
try:
page_obj = paginator.page(page_number)
except PageNotAnInteger:
page_obj = paginator.page(1)
except EmptyPage:
page_obj = paginator.page(paginator.num_pages)
return render(request, 'list.html', {'page_obj': page_obj})
Template Example
<ul>
{% for item in page_obj.object_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<div>
{% if page_obj.has_previous %}
<a href="?p={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
{% if page_obj.has_next %}
<a href="?p={{ page_obj.next_page_number }}">Next</a>
{% endif %}
</div>