python – How do i use Django session to read/set cookies? – Education Career Blog

I am trying to use the Django sessions to read and set my cookies, but when i do the following the program just does not respond!

sessionID = request.session”userid”

The program does not pass this point!

Any ideas?

,

First, Django already creates a user object for you so you don’t need to store it in the session. Just access it as:

request.user

For example, to get the username you would use:

request.user.username

Next, if you want to store information in the session you don’t need to worry about it at the cookie level. Simply write key / value pairs to the request.session dictionary.

Here are some examples from the Django documentation.

Edit: The reason your program isn’t responding is because a KeyError exception is being raised. ‘userid’ doesn’t exist as a key in the session dictionary (unless you have added it yourself).

This is why it is better to program dictionary reads like this:

id = request.session.get('somekey', False)

Which will return False if ‘somekey’ doesn’t exist in the dictionary.

Leave a Comment