[Fixed]-Clearing sessions in django_session table without logging out current users

19👍

The Django documentation states (emphasis from me):

Clearing the session store

As users create new sessions on your website, session data can
accumulate in your session store. If you’re using the database
backend, the django_session database table will grow. If you’re using
the file backend, your temporary directory will contain an increasing
number of files.

To understand this problem, consider what happens with the database
backend. When a user logs in, Django adds a row to the django_session
database table. Django updates this row each time the session data
changes. If the user logs out manually, Django deletes the row. But if
the user does not log out, the row never gets deleted. A similar
process happens with the file backend.

Django does not provide automatic purging of expired sessions.
Therefore, it’s your job to purge expired sessions on a regular basis.
Django provides a clean-up management command for this purpose:
clearsessions. It’s recommended to call this command on a regular
basis, for example as a daily cron job.

Note that the cache backend isn’t vulnerable to this problem, because
caches automatically delete stale data. Neither is the cookie backend,
because the session data is stored by the users’ browsers.

Found this link in Abid A’s answer.

The clearsessions command

Can be run as a cron job or directly to clean out expired sessions.

So it won’t log off every user.

As mentioned by Kevin Christopher Henry in a comment and in the other possible duplicate of your question flagged by e4c5.

16👍

  1. Django 1.6 or Above

    python manage.py clearsessions

  2. Django 1.5 or lower

    python manage.py cleanup

  3. From Django Shell

    from django.contrib.sessions.models import Session
    Session.objects.all().delete()
    
  4. django-session-cleanup
    cronJob

  5. clearing session in logout( based on session key present in request)

from django.contrib.sessions.models import Session  
session_key = request.data['sessionKey']
session = Session.objects.get(session_key=session_key)
Session.objects.filter(session_key=session).delete()
Session.objects.all().delete()

-2👍

The newer versions of Django allow:

request.session.clear()

Leave a comment