javascript.txt 2.4 KB

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