Where should custom middleware.py be placed?

Hi, I just created a custom middleware so that the session key would not write to cookies at all, call it middleware.py (under the project folder, not inside any app):

import time
from importlib import import_module

from django.conf import settings
from django.contrib.sessions.backends.base import UpdateError
from django.contrib.sessions.exceptions import SessionInterrupted
from django.utils.http import http_date
from django.contrib.sessions.middleware import SessionMiddleware

class NoCookiesSessionMiddleware(SessionMiddleware):
    def __init__(self, get_response):
        super().__init__(get_response)

    def process_request(self, request):
        request.session = self.SessionStore(None) #force create a new session

    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie or delete
        the session cookie if the session has been emptied.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
        except AttributeError:
            return response
        # First check if we need to delete this cookie.
        # The session should be deleted only if the session is entirely empty.
        if empty:
            pass
        else:
            # If the session was accessed, it must be varied on, regardless of
            # whether it was modified or will be saved.
            if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = http_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 5xx responses.
                if response.status_code < 500:
                    try:
                        request.session.save()
                    except UpdateError:
                        raise SessionInterrupted(
                            "The request's session was deleted before the "
                            "request completed. The user may have logged "
                            "out in a concurrent request, for example."
                        )
                    # With a session cookie set, it must be varied on.
        return response

However, when I try to add it into MIDDLEWARE in settings.py:


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    #'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    #'django.contrib.auth.middleware.AuthenticationMiddleware',
    #'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'middleware.NoCookiesSessionMiddleware'
]

and then python3 manage.py runserver, the following error occurs:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/servers/basehttp.py", line 49, in get_internal_wsgi_application
    return import_string(app_path)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/utils/module_loading.py", line 30, in import_string
    return cached_import(module_path, class_name)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/utils/module_loading.py", line 15, in cached_import
    module = import_module(module_path)
  File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/importlib/__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1406, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1371, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1342, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 938, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 759, in exec_module
  File "<frozen importlib._bootstrap>", line 491, in _call_with_frames_removed
  File "/Users/testuser/Desktop/testworld/testproject/testproject/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/handlers/wsgi.py", line 118, in __init__
    self.load_middleware()
    ~~~~~~~~~~~~~~~~~~~~^^
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/handlers/base.py", line 41, in load_middleware
    middleware = import_string(middleware_path)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/utils/module_loading.py", line 30, in import_string
    return cached_import(module_path, class_name)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/utils/module_loading.py", line 15, in cached_import
    module = import_module(module_path)
  File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/importlib/__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1406, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1371, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1335, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'middleware'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/threading.py", line 1082, in _bootstrap_inner
    self._context.run(self.run)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/threading.py", line 1024, in run
    self._target(*self._args, **self._kwargs)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
    ~~^^^^^^^^^^^^^^^^^
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/management/commands/runserver.py", line 143, in inner_run
    handler = self.get_handler(*args, **options)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 31, in get_handler
    handler = super().get_handler(*args, **options)
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/management/commands/runserver.py", line 73, in get_handler
    return get_internal_wsgi_application()
  File "/Users/testuser/Desktop/testworld/lib/python3.14/site-packages/django/core/servers/basehttp.py", line 51, in get_internal_wsgi_application
    raise ImproperlyConfigured(
    ...<2 lines>...
    ) from err
django.core.exceptions.ImproperlyConfigured: WSGI application 'testproject.wsgi.application' could not be loaded; Error importing module.

What’s wrong with the middleware? (eg: Wrong location? or the middleware class should extend some parent class specific for custom middleware?)

If it is caused by wrong location, where should middleware.py be put?

What exactly are you trying to do with this middleware?

I would like to suggest that you stop trying to over-manage the session object. Learn how to do what you need to do by working with Django instead of trying to work around it. Things are going to go a lot easier that way.

Hi, I was trying to build a API server with JWT auth (token only auth), I’m using database based sessions.

Django original behaviour : When session saves, it also saves the session id to client cookie

What I want : Keep all django sessions original behaviour, except cookies : don’t send the session id to client via cookies, but send it via my API response (so next time client would submit the session id from some variables in client javascript instead of from cookies)

I was considering 2 options:

  1. Use Django only
  2. Use Django Rest Framework

I’m not refusing Django Rest Framework, but want to try a Django only solution first (which I think less other frameworks to use is easier for new teammates to pickup and easier to maintain), and hence I just try to create a custom middleware NoCookiesSessionMiddleware to simulate original SessionMiddleware behaviours except saving session id into client cookies (and NoCookiesSessionMiddleware isn’t a new thing actually, it is just the Django original SessionMiddleware but delete the cookies related codes).

Was I doing it in wrong way :face_with_raised_eyebrow:?

There’s no need to do this. The cookies are sent with the client request.

Again, work with Django - don’t try to work around it.

The whole point of how Django manages sessions is that the management of those sessions are completely transparent to the application.