You can access the Django session framework from the browser by accessing the session attribute of the HttpRequest object in a view function. The session attribute acts like a standard Python dictionary. You add items to and get items from the session using standard dictionary syntax.
By the Way
The session dictionary accepts any pickleable Python object. This functionality allows you to store a variety of data in the session.
For example, the following code snippet creates, retrieves, and deletes a key named i_feel in the session:
request.session['i_feel'] = 'happy' mood = request.session['i_feel'] del request.session['i_feel']
By the Way
When you define names for entries in the session store, avoid using names that begin with the underscore character. Names beginning with an underscore are reserved for Django.
The following line of code checks to see if the i_feel key exists in the session:
if 'i_feel' in request.session: . . .
You can also use the get(key, default=None), keys(), and items() dictionary functions on the session attribute.
Setting values in the session attribute stores them in the session, where they can be accessed by other view functions that the user accesses.
Try It Yourself: Set and Retrieve Session DataIn this section, you will modify the add_blog() function to add a session_blog key to the session when the user creates a new blog. Then you will add a check to the add_blog() function to determine if the user has already added a blog entry. Finally, you will redirect the add_blog request to the generic blog_details view of the blog that was already created. Follow these steps to make the changes to the add_blog() view function:
Listing 16.2. The update_blog() Function in the iFriends/People/views.py File
Listing 16.3. Full Contents of the iFriends/templates/People/update_blog_form.html Template File
Listing 16.4. A Portion of the add_blog() Function in the iFriends/People/views.py File
|