Debian Codegraph @

docs/ref/contrib/admin/javascript.txt

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