In a previous post I wrote
a Vanilla JS function for parsing all the current cookies. Since then a couple
of things have happened:
- I realised it was not safe
- JS in browsers got better [and I got better at it]
It was not safe in as much as it parsed the cookie value once and retained the
value. If you were, for instance, using a SPA, Django might update the CSRF
token at any point, making your value stale. So instead, I've updated the
function to get just one value, and perform parsing on each call.
Serialisers are increasingly important now that most web apps are just APIs for
Serialisers help to reduce your living code objects into simpler types that can
be encoded in your serialisation format [typically JSON]. After all, JSON has
no date or time types, no classes, etc.
In the Django world, modern REST API libraries separate their Serialiser from
the views, and go to great lengths to make them easy to configure, simple to
use, and fast. They also support returning your "deflated" data into live code
I was recently helping someone who was trying to learn about building web
sites, and was trying to avoid learning too many things at once, so opted to
avoid JS libraries for now.
As the discussion progressed, they ran into Django's Cross Site Request
Forgery protection which
So, as I was about to link them to the part of the docs that shows how to add
the CSRF token from the cookie to your headers, I realised it all assumes
you're using jQuery.
Django provides many decorators for use throughout your project. They can be
great time savers, and mastering them can help you DRY your code considerable.
However, they often confuse people as to how they work, or how to write their
In this post I plan to walk through an example of building up a simple
decorator that tests if the user has a specific permission, and if not
returning a 403 Forbidden response.