Django DRY Javascript Urls

We are announcing a new library that adds ability to build your Django urls in Javascript without copy-pasting or building urls by string conctatenation.

Don’t-Repeat-Yourself (or DRY) is one of the main principles of Django framework and writing applications with Django. The DRY principle is stated as “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” DRY aids with maintenance and understanding of the application code.

Django’s solution for not hardcoding urls in HTML is called named url patterns which allows you to reference paths by a predefined name. Sadly, no such logic exists for Javascript as Javascript generally is not run through Django template processing due to overhead considerations.
And so, developers hardcode their urls for AJAX requests which is not only repeating the same information already defined elsewhere, but can also make parametrized urls impossible to read as string concatentation is excessively used.

We have built upon a solution already created by Marco Louro (mlouro on GitHub) and used his Javascript reverse function, but added a way to automatically build a list of all Django urls in your project and output them to a Javascript file.

You can easily hook into your build process by using the management command provided. The command looks through urls defined in your Django project and builds a list of the paths. It also recognizes where the parameters are expected and converts the parameters, named or otherwise, into an easier format for Javascript to process.

After including the library and the resulting files to your webpage, you can build your urls as such:

$.post(dutils.urls.resolve('article_edit', {article_id: 171}), ...

The installation and usage instructions can be found on GitHub

The library can be found on GitHub:
https://github.com/Dimitri-Gnidash/django-js-utils

Post a Comment

Your email is never shared. Required fields are marked *

*
*