Django — Sessions
What are Sessions?
Sessions store data on the server for each user, identified by a session ID in a cookie.
Session Settings
# settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_AGE = 1209600 # 2 weeks in seconds
SESSION_SAVE_EVERY_REQUEST = False
Using Sessions in Views
def my_view(request):
# Set session data
request.session['username'] = 'john'
request.session['last_visit'] = datetime.now().isoformat()
# Get session data
username = request.session.get('username', 'Guest')
# Delete session data
del request.session['username']
# Flush session
request.session.flush()
Session Methods
| Method | Description |
|---|---|
| get(key, default) | Get value |
| set(key, value) | Set value |
| pop(key) | Get and delete |
| keys() | All keys |
| items() | All items |
| clear() | Clear all |
| flush() | Delete session |
| exists(session_key) | Check if exists |
Session in Templates
{% if request.session.username %}
<p>Welcome, {{ request.session.username }}!</p>
{% endif %}
Mini Practice
- Store and retrieve session data
- Use session for user preferences
- Clear session on logout
- Check session expiration
Up Next
Continue with Cookies — working with cookies.
Related Topics
Frequently Asked Questions about Sessions
What is Sessions in Django?
Sessions is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sessions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sessions.
Why is Sessions important in Django?
Sessions is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.