The fact that Django comes with CSRF protection is extremely nice. Unless, of course, your hobby is exploiting websites, in which case get off my site. For the rest of us, thwart those baddies by using Django's
CsrfViewMiddleware and the
csrf_token tag. But when you do, keep in mind what that changes on your webpages. The
csrf_token tag sets a cookie. So, that begs the question:
What about legitimate users that have their cookies disabled?
Sure, it's a fringe case, but let's address it, because it's easy. If Django can't set that cookie when the user submits the form, by default the user will see a 403 Forbidden error page that looks something like this:
Yuck. For all intents and purposes, you just did the webdeveloper's equivalent of backhanding one of your unsuspecting users. It was probably some elderly grandma on a locked-down public library computer who now thinks she accidentally caused the local police to be notified. Are you proud of yourself?
Django, like usual, has your back. You can add something like this to your settings.py file:
CSRF_FAILURE_VIEW = 'myproject.path.to.friendly_csrf_failure_view'
Then create a view method with the name and path you supplied in that variable. Django will use your view instead of the sinister-looking 403 Forbidden page that scares grandma. Instead you can send her to a calming sky-blue page with a big yellow smiley face that asks if maybe she's disabled her cookies. Thanks Django for providing a way out.
Here's an example of what to do using JQuery. We also need jquery.cookie.js, which can be found here:
With JQuery and jquery.cookie.js included on the page, add something like this code snippet to the section of your form page:
And that's it. A few lines of code and your site is grandma-worthy. If cookies are disabled, the user will never see a 403 Forbidden. Instead, the user will get instructions and the form won't be active until they follow them. The instructions open in a separate window, so the user doesn't leave your form page. For bonus friendliness, you can also do the following:
If you would like to see this in action, disable your cookies and visit my Contact Me page. And while you're there, you know, you could actually go ahead and re-enable cookies and contact me for real. Just saying.