Setting test cookies

As a convenience, Django provides an easy way to test whether the user's browser accepts cookies. Just call the set_test_cookie() method of request.session in a view, and call test_cookie_worked() in a subsequent view-not in the same view call.

This awkward split between set_test_cookie() and test_cookie_worked() is necessary due to the way cookies work. When you set a cookie, you can't actually tell whether a browser accepted it until the browser's next request. It's good practice to use delete_test_cookie() to clean up after yourself. Do this after you've verified that the test cookie worked.

Here's a typical usage example:

def login(request): if request.method == 'POST': if request.session.test_cookie_worked(): request.session.delete_test_cookie() ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.