I have this code in my project that assigns a unique id to an anomymous user and saves it in a session:
user_id = str(uuid.uuid4())[:5]
request.session['nonuserid'] = user_id
Documentation says that sessions are stored in my database. I thought it would save it in django_session
table. However, everytime a unique is created and saved in session(above code), no row is added to that table.
Then I checked cookies in Resources
. There is no key with name nonusedid
. Just some sessionid
So, where does it store the session data I created?
Relevant part of Settings.py
MIDDLEWARE_CLASSES = (
# Default Django middleware.
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DJANGO_APPS = (
# Default Django apps:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache. When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute.
Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as the server. Read through this article to find out more about cookies and sessions and how they are different from each other.
Objects cannot be stored in session from Django 1.6 or above. If you don't want to change the behavior of the cookie value(of a object), you can add a dictionary there. This can be used for non database objects like class object etc. Hope it will help you!
I thought it would save it in django_session table. However, everytime a unique is created and saved in session(above code), no row is added to that table.
Hopefully a new row is not added each time you add a key/value to the current session. Session's data are stored in serialized form (in the django_session.session_data
field), and a new row is added only when a new session is started - all subsequent writes to the session will only update the session_data
field's content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With