[Django]-What is the difference between a cookie and a session in django?

33👍

A cookie is something that sits on the client’s browser and is merely a reference to a Session which is, by default, stored in your database.

The cookie stores a random ID and doesn’t store any data itself. The session uses the value in the cookie to determine which Session from the database belongs to the current browser.

This is very different from directly writing information on the cookie.

Example:

httpresponse.set_cookie('logged_in_status', 'True')
# terrible idea: this cookie data is editable and lives on your client's computer


request.session['logged_in_status'] = True
# good idea: this data is not accessible from outside. It's in your database.

12👍

A cookie is not a Django, or Python specific technology. A cookie is a way of storing a small bit of state in your client’s browser. It’s used to supplement (or hack around, depending on your point of view) HTTP, which is a stateless protocol. There are all sorts of limitations here, other domains cant read your cookies, you can only store a a few k of data (just how much depends on the browser!), etc, etc.

A cookie can be used to store a session key. A session is a collection of user state that’s stored server side. The session key gets passed back to the server, which allows you to look up that session’s state. Most web frameworks (not just Django) will have some sort of session concept built in. This lets you add server-side state to an HTTP conversation.

👤mblinn

0👍

To complement ‘Yuji ‘Tomita’ Tomita’s answer

with cookies You can set any information on client browser
not just id (session id),

cookies are limited (size limited to kb), less secure and less flexible compared to sessions.

django sessions are based on cookies, django uses a cookie to save session id on client

sessions are not limited to data size (because they are saved on db of server), more secure and more flexible.

Leave a comment