Another problem with cookies is that you are not guaranteed that the browser will accept cookies. Some browsers disable cookies as a security precaution. If your website requires access to cookies or to the session framework cookie, you may want to add code to your login to verify that cookies are enabled.
Django provides the set_test_cookie(), test_cookie_worked(), and delete_test_cookie() functions to the HttpRequest.session object to aid in this task. The set_test_cookie() function attempts to set a test cookie in the browser. The test_cookie_worked() function attempts to retrieve the test cookie, and the delete_test_cookie() function deletes the cookie.
Watch Out!
The test_cookie_worked() function needs to be used in a different request than the set_test_cookie() function, because the cookie typically isn't saved until after the request is finished.
Try It Yourself: Implement Test Cookies to Verify That the Browser Will Support CookiesIn this section, you will modify the login_user() view function to have it set a test cookie during the GET request and verify that the cookie is set in the POST request before logging in the user. Follow these steps to modify the GET and POST handlers of the login_user() view function to implement a test cookie:
Listing 16.1. The login_user() Function in the iFriends/Home/views.py File
|