BartoNaz
BartoNaz

Reputation: 2923

Disable sessions/cookies for selected pages in Django

On my website, cookies and sessions are required only for authentication in the admin section. For all other urls I don't want to store cookies or run the session middleware, as it creates an unnecessary DB read/write on every http request.

Is there a way to disable the session middleware for selected pages without the authentication middleware complaining about missing session middleware?

Upvotes: 2

Views: 1631

Answers (1)

solarissmoke
solarissmoke

Reputation: 31484

It creates an unnecessary DB read/write on every http request.

This is not correct. Django only creates a session if you attempt to write something to it - until then no session is created an no session cookie is set. From the documentation:

By default, Django only saves to the session database when the session has been modified.

Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.

(SESSION_SAVE_EVERY_REQUEST defaults to False).

So for the kind of thing you are describing, sessions will never be created for users who don't access the admin, and there will be no database overhead. The only small overhead will be the middleware that checks for a session cookie.

Upvotes: 3

Related Questions