tags:

views:

884

answers:

1

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?

+4  A: 

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.

Van Gale
Your code is wrong. request.session['somekey', False] simply tries ('somekey', False) tuple as a key. It should be get(key, default).
muhuk
Bleh, thanks muhuk. My brain was faster than my typing.
Van Gale