Whatever Whenever Tech insights, coding tips, and AI stuff
Home New Post
Profile
Login Register

Select a category for your post

Click tags to select/deselect

Markdown supported: # Heading, **bold**, *italic*, `code`, - list items, etc.
Tip: Paste images directly from clipboard or drag-and-drop to upload!

Auto logout a user after specific time in Django.

1. Install dependencies
shell
pip install django-auto-logout
# pip install pytz 
2. Append to settings middlewares
python
MIDDLEWARE = [
    ...
    'django_auto_logout.middleware.auto_logout',
]

Make sure that the following middlewares are used before doing this:

  • mdjango.contrib.sessions.middleware.SessionMiddleware
  • django.contrib.auth.middleware.AuthenticationMiddleware
  • django.contrib.messages.middleware.MessageMiddleware
3. Modify context_processors in settings.py:
python
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # !!! Add this !!!
                'django_auto_logout.context_processors.auto_logout_client',
            ],
        },
    },
]
4. Add this to your templates (will add a redirect script to your html):
html
{{ redirect_to_login_immediately }}
5. Add below lines in settings.py
python
AUTO_LOGOUT = {
    'IDLE_TIME': 600, 
    'REDIRECT_TO_LOGIN_IMMEDIATELY': True,
    'MESSAGE': 'The session has expired. Please login again to continue.'
    }
6. Display messages in templates:
html
{% for message in messages %}
    <div class="message {{ message.tags }}">
        {{ message }}
    </div>
{% endfor %}
Cancel

Add New Category

Add New Tag

Home Search | RSS Sitemap

© 2026 whatever.asia