0
0
Djangoframework~30 mins

Session expiry behavior in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Session Expiry Behavior in Django
📖 Scenario: You are building a simple Django web application that requires users to log in. To improve security, you want to control how long a user's session lasts before they are automatically logged out.
🎯 Goal: Learn how to set up session expiry behavior in Django by configuring session timeout and applying it in your views.
📋 What You'll Learn
Create a Django view that sets a session variable
Configure a session expiry time in seconds
Implement logic to check session expiry
Ensure the session expires after the configured time
💡 Why This Matters
🌍 Real World
Web applications often need to manage user sessions securely to protect user data and control access.
💼 Career
Understanding session management is essential for backend developers working with Django or similar web frameworks.
Progress0 / 4 steps
1
Create a Django view that sets a session variable
Create a Django view function called set_session that takes request as a parameter and sets a session variable user_id with the value 42.
Django
Need a hint?

Use request.session['user_id'] = 42 inside the view function.

2
Configure a session expiry time in seconds
Inside the set_session view, add a line to set the session expiry time to 300 seconds (5 minutes) using request.session.set_expiry(300).
Django
Need a hint?

Use request.session.set_expiry(300) to set the session timeout.

3
Implement logic to check session expiry
Create a Django view function called check_session that takes request as a parameter. Inside it, check if 'user_id' exists in request.session. If it exists, return an HttpResponse with text 'Session active'. Otherwise, return 'Session expired'.
Django
Need a hint?

Use if 'user_id' in request.session: to check session existence.

4
Complete the Django URL configuration
In your Django urls.py file, import the views set_session and check_session. Add two URL patterns: one for path 'set/' mapped to set_session, and one for path 'check/' mapped to check_session.
Django
Need a hint?

Use path('set/', set_session) and path('check/', check_session) in urlpatterns.