Django MultiRangeField and MultiRangeFormField

This post was published more than a few years ago (on 2014-06-01) and may contain inaccurate technical information, outmoded thoughts, or cringe takes. Proceed at your own risk.

I’m building a website, and needed a way to save a list of pages and page ranges from a book or magazine. I wanted to to be a little more strict than just saving it as a string without any cleanup or validation, so I wrote a custom Django model field (and accompanying form field).

It either just validates and cleans so that

[crayon-64cc43bdc827f065817020/]

becomes the tidy

[crayon-64cc43bdc8284268839215/]

…or, if you comment out the raising of the ValidationError in the form field’s validate() method, it will actually clean up any junk characters for you, so even this horrible mess:

[crayon-64cc43bdc8286559892587/]

gets cleaned to

[crayon-64cc43bdc8288635303413/]

Enjoy!