django sessions for beginners
- Setting up Sessions in Django:
Django sessions allow you to store and retrieve arbitrary data on a per-site-visitor basis. To use sessions, ensure the following configurations are in place:
- Configure Django's Settings:
Open your Django project's settings.py
file and ensure the django.contrib.sessions
app is included in the INSTALLED_APPS
list:
python
INSTALLED_APPS = [
# ... other apps
'django.contrib.sessions',
# ... other apps
]
- Session Middleware:
In the same settings.py
file, ensure that 'django.contrib.sessions.middleware.SessionMiddleware'
is included in the MIDDLEWARE
list. It should generally come after django.contrib.auth.middleware.AuthenticationMiddleware
:
python
MIDDLEWARE = [
# ... other middleware
'django.contrib.sessions.middleware.SessionMiddleware',
# ... other middleware
]
- Save Changes:
Save the settings.py
file after making these changes.
- Apply Database Migrations:
Run the following command to apply migrations for the sessions:
bash
python manage.py migrate
- Using Sessions in Views:
Now, you can use sessions to store and retrieve data in your views. Import django.contrib.sessions
:
python
from django.contrib.sessions.models import Session
- Storing Data in Sessions:
To store data in the session, access the request.session
dictionary-like object in your view and assign values to it:
python
# Storing data
request.session['key'] = 'value'
- Retrieving Data from Sessions:
Retrieve the stored data by accessing the session dictionary using the same key:
python
# Retrieving data
stored_value = request.session.get('key')
- Deleting Data from Sessions:
To delete a specific key from the session, use the del
keyword:
python
# Deleting data
del request.session['key']
Clearing Session Data:
To clear all session data, use the
clear()
method:```python
Clear all session data
request.session.clear() ```
Session Expiry and Settings:
Customize session-related settings such as expiry time, cookie settings, and more in the
settings.py
file by using attributes likeSESSION_COOKIE_AGE
,SESSION_SAVE_EVERY_REQUEST
, etc.