django sessions for beginners

  1. 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:

  1. 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 ]

  1. 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 ]

  1. Save Changes:

Save the settings.py file after making these changes.

  1. Apply Database Migrations:

Run the following command to apply migrations for the sessions:

bash python manage.py migrate

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

  1. 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'

  1. 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')

  1. Deleting Data from Sessions:

To delete a specific key from the session, use the del keyword:

python # Deleting data del request.session['key']

  1. Clearing Session Data:

    To clear all session data, use the clear() method:

    ```python

    Clear all session data

    request.session.clear() ```

  2. Session Expiry and Settings:

    Customize session-related settings such as expiry time, cookie settings, and more in the settings.py file by using attributes like SESSION_COOKIE_AGE, SESSION_SAVE_EVERY_REQUEST, etc.