javascript.txt 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. ======================================
  2. JavaScript customizations in the admin
  3. ======================================
  4. .. _admin-javascript-inline-form-events:
  5. Inline form events
  6. ==================
  7. You may want to execute some JavaScript when an inline form is added or removed
  8. in the admin change form. The ``formset:added`` and ``formset:removed`` events
  9. allow this. ``event.detail.formsetName`` is the formset the row belongs to.
  10. For the ``formset:added`` event, ``event.target`` is the newly added row.
  11. .. versionchanged:: 4.1
  12. In older versions, the event was a ``jQuery`` event with ``$row`` and
  13. ``formsetName`` parameters. It is now a JavaScript ``CustomEvent`` with
  14. parameters set in ``event.detail``.
  15. In your custom ``change_form.html`` template, extend the
  16. ``admin_change_form_document_ready`` block and add the event listener code:
  17. .. code-block:: html+django
  18. {% extends 'admin/change_form.html' %}
  19. {% load static %}
  20. {% block admin_change_form_document_ready %}
  21. {{ block.super }}
  22. <script src="{% static 'app/formset_handlers.js' %}"></script>
  23. {% endblock %}
  24. .. code-block:: javascript
  25. :caption: app/static/app/formset_handlers.js
  26. document.addEventListener('formset:added', (event) => {
  27. if (event.detail.formsetName == 'author_set') {
  28. // Do something
  29. }
  30. });
  31. document.addEventListener('formset:removed', (event) => {
  32. // Row removed
  33. });
  34. Two points to keep in mind:
  35. * The JavaScript code must go in a template block if you are inheriting
  36. ``admin/change_form.html`` or it won't be rendered in the final HTML.
  37. * ``{{ block.super }}`` is added because Django's
  38. ``admin_change_form_document_ready`` block contains JavaScript code to handle
  39. various operations in the change form and we need that to be rendered too.
  40. Supporting versions of Django older than 4.1
  41. --------------------------------------------
  42. If your event listener still has to support older versions of Django you have
  43. to use jQuery to register your event listener. jQuery handles JavaScript events
  44. but the reverse isn't true.
  45. You could check for the presence of ``event.detail.formsetName`` and fall back
  46. to the old listener signature as follows:
  47. .. code-block:: javascript
  48. function handleFormsetAdded(row, formsetName) {
  49. // Do something
  50. }
  51. $(document).on('formset:added', (event, $row, formsetName) => {
  52. if (event.detail.formsetName) {
  53. // Django >= 4.1
  54. handleFormsetAdded(event.target, event.detail.formsetName)
  55. } else {
  56. // Django < 4.1, use $row and formsetName
  57. handleFormsetAdded($row.get(0), formsetName)
  58. }
  59. })