JavaScript

While most of Django core is Python, the admin and gis contrib apps contain JavaScript code.

在编写用于包含在 Django 中的 JavaScript 代码时,请遵循以下编码标准:

编码风格

  • Please conform to the indentation style dictated in the .editorconfig file. We recommend using a text editor with EditorConfig support to avoid indentation and whitespace issues. Most of the JavaScript files use 4 spaces for indentation, but there are some exceptions.
  • When naming variables, use camelCase instead of underscore_case. Different JavaScript files sometimes use a different code style. Please try to conform to the code style of each file.
  • Use the ESLint code linter to check your code for bugs and style errors. ESLint will be run when you run the JavaScript tests. We also recommended installing a ESLint plugin in your text editor.
  • Where possible, write code that will work even if the page structure is later changed with JavaScript. For instance, when binding a click handler, use $('body').on('click', selector, func) instead of $(selector).click(func). This makes it easier for projects to extend Django’s default behavior with JavaScript.

JavaScript 补丁

Django 的管理系统利用 jQuery 框架来增强管理界面的功能。同时,强调管理 JavaScript 的性能和尽量减少整体管理媒体文件的大小。

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:

  1. QUnit.module('magicTricks', {
  2. beforeEach: function() {
  3. const $ = django.jQuery;
  4. $('#qunit-fixture').append('<button class="button"></button>');
  5. }
  6. });
  7. QUnit.test('removeOnClick removes button on click', function(assert) {
  8. const $ = django.jQuery;
  9. removeOnClick('.button');
  10. assert.equal($('.button').length, 1);
  11. $('.button').click();
  12. assert.equal($('.button').length, 0);
  13. });
  14. QUnit.test('copyOnClick adds button on click', function(assert) {
  15. const $ = django.jQuery;
  16. copyOnClick('.button');
  17. assert.equal($('.button').length, 1);
  18. $('.button').click();
  19. assert.equal($('.button').length, 2);
  20. });

Please consult the QUnit documentation for information on the types of assertions supported by QUnit.

运行测试

JavaScript 测试可以在网页浏览器或命令行中运行。

通过网页浏览器进行测试

To run the tests from a web browser, open up js_tests/tests.html in your browser.

在运行测试时测量代码覆盖率,您需要通过 HTTP 查看该文件。要查看代码覆盖率:

  • Execute python -m http.server from the root directory (not from inside js_tests).
  • 在您的网页浏览器中打开 http://localhost:8000/js_tests /tests.html。

通过命令行进行测试

To run the tests from the command line, you need to have Node.js installed.

After installing Node.js, install the JavaScript test dependencies by running the following from the root of your Django checkout:

Linux/MacOS     Windows

  1. $ npm install
  1. ...\> npm install

然后使用以下命令运行测试:

Linux/MacOS     Windows

  1. $ npm test
  1. ...\> npm test