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() return HttpResponse("You're logged in.") else: return HttpResponse("Please enable cookies and try again.") request.session...