While most of Django core is Python, the admin and gis contrib apps contain JavaScript code.
Please follow these coding standards when writing JavaScript code for inclusion in Django.
Django’s admin system leverages the jQuery framework to increase the capabilities of the admin interface. In conjunction, there is an emphasis on admin JavaScript performance and minimizing overall admin media file size. Serving compressed or “minified” versions of JavaScript files is considered best practice in this regard.
To that end, patches for JavaScript files should include both the original code for future development (e.g. foo.js), and a compressed version for production use (e.g. foo.min.js). Any links to the file in the codebase should point to the compressed version.
To simplify the process of providing optimized JavaScript code, Django includes a handy Python script which should be used to create a “minified” version. To run it:
$ pip install closure
$ python django/contrib/admin/bin/compress.py
Behind the scenes, compress.py is a front-end for Google’s Closure Compiler which is written in Java. The Closure Compiler library is not bundled with Django, but you can install it using pip as done above. The Closure Compiler library requires Java 7 or higher.
Please don’t forget to run compress.py and include the diff of the minified scripts when submitting patches for Django’s JavaScript.
Django’s JavaScript tests can be run in a browser or from the command line. The tests are located in a top level js_tests directory.
Django’s JavaScript tests use QUnit. Here is an example test module:
module('magicTricks', {
beforeEach: function() {
var $ = django.jQuery;
$('#qunit-fixture').append('<button class="button"></button>');
}
});
test('removeOnClick removes button on click', function(assert) {
var $ = django.jQuery;
removeOnClick('.button');
assert.equal($('.button').length === 1);
$('.button').click();
assert.equal($('.button').length === 0);
});
test('copyOnClick adds button on click', function(assert) {
var $ = django.jQuery;
copyOnClick('.button');
assert.equal($('.button').length === 1);
$('.button').click();
assert.equal($('.button').length === 2);
});
Please consult the QUnit documentation for information on the types of assertions supported by QUnit.
The JavaScript tests may be run from a web browser or from the command line.
To run the tests from a web browser, open up js_tests/tests.html in your browser.
To measure code coverage when running the tests, you need to view that file over HTTP. To view code coverage:
Mar 31, 2016