Tags - javascript

Modern Vanilla JS for cookie parsing

In a previous post I wrote a Vanilla JS function for parsing all the current cookies. Since then a couple of things have happened:

  1. I realised it was not safe
  2. 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.

Serialiser in a hurry

Serialisers are increasingly important now that most web apps are just APIs for the JavaScript to consume.

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 objects.

Vanilla JS meets Django's CSRF

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 stumped them.

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.

Wrapping views with decorators

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 own.

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.

Decorator basics.