46

Does this table need to be purged or is it taken care of automatically by Django?

nemesisdesign
  • 8,159
  • 12
  • 58
  • 97

5 Answers5

62

Django does NOT provide automatic purging. There is however a handy command available to help you do it manually: Django docs: Clearing the session store

python manage.py clearsessions
Abid A
  • 7,588
  • 4
  • 32
  • 32
  • 7
    If you use Django 1.5 or lower, you can use python manage.py cleanup – Josir Jun 10 '15 at 00:16
  • 3
    I was in my psql and found out that `TRUNCATE django_session;` also works. – Alper Oct 21 '17 at 20:30
  • I would check beforehand the sessions before deleting: in mysql `select*from django_session;` or to see how many there are `select count (*)from django_session;` – Timo Mar 15 '18 at 08:59
  • 3
    @Alper be careful with truncation of the table, this will effectively clear the session for every user of your system, not just the ones that are expired which is what **clearsessions** does. Sometimes this is fine, but my bet would be that you don't want to wipe valid session data for every single person... say a person who logged in 5 minutes ago. – ViaTech Oct 17 '18 at 19:49
  • @ViaTech Oh, in this case (for packing an old website) this was a perfectly fine outcome. – Alper Oct 18 '18 at 08:06
22
  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 cornJob
Roshan Bagdiya
  • 2,048
  • 21
  • 41
2

On my development server, I prefer a database command over python manage.py clearsessions because you delete all sessions, not just the expired ones (here: MySQL). To login into your database and do:

truncate table django_session;

BTW, session is not a database, but a table (django_session) and an app (django.contrib.sessions).

Timo
  • 2,922
  • 3
  • 29
  • 28
0

I know this post is old but I tried this command/attribute and it worked for me.

In the 'base.html' file, I inserted: {{ request.session.clear_expired }}

This clears expired records from the django_session table when the user clicks on any link in the template after the session expires.

Even so, it is necessary to create a routine to clear expired records over a period longer than one day. This is necessary to clear logs when user closes browser with open sessions.

I used Django 3.2.4

0

Other method:

I'm using Django 3.2 and i recommend using the django-auto-logout package.

It allows active time and idle time session control.

In the template you can use variables together with Javascript.

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30792604) – Simas Joneliunas Jan 14 '22 at 15:48