summaryrefslogtreecommitdiff
path: root/docs/ref/contrib/admin/javascript.txt
blob: f953b269adbfd0ba54965ecf8f25cfd1e6e47d37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
======================================
JavaScript customizations in the admin
======================================

.. _admin-javascript-inline-form-events:

Inline form events
==================

.. versionadded:: 1.9

You may want to execute some JavaScript when an inline form is added or removed
in the admin change form. The ``formset:added`` and ``formset:removed`` jQuery
events allow this. The event handler is passed three arguments:

* ``event`` is the ``jQuery`` event.
* ``$row`` is the newly added (or removed) row.
* ``formsetName`` is the formset the row belongs to.

The event is fired using the :ref:`django.jQuery namespace
<contrib-admin-jquery>`.

In your custom ``change_form.html`` template, extend the
``admin_change_form_document_ready`` block and add the event listener code:

.. code-block:: html+django

    {% extends 'admin/change_form.html' %}

    {% block admin_change_form_document_ready %}
    {{ block.super }}
    <script type="text/javascript">
    (function($) {
        $(document).on('formset:added', function(event, $row, formsetName) {
            if (formsetName == 'author_set') {
                // Do something
            }
        });

        $(document).on('formset:removed', function(event, $row, formsetName) {
            // Row removed
        });
    })(django.jQuery);
    </script>
    {% endblock %}

Two points to keep in mind:

* The JavaScript code must go in a template block if you are inheriting
  ``admin/change_form.html`` or it won't be rendered in the final HTML.
* ``{{ block.super }}`` is added because Django's
  ``admin_change_form_document_ready`` block contains JavaScript code to handle
  various operations in the change form and we need that to be rendered too.

Sometimes you'll need to work with ``jQuery`` plugins that are not registered
in the ``django.jQuery`` namespace. To do that, simply change how the code
listens for events. Instead of wrapping the listener in the ``django.jQuery``
namespace, just listen to the event triggered from there. For example:

.. code-block:: html+django

    {% extends 'admin/change_form.html' %}

    {% block admin_change_form_document_ready %}
    {{ block.super }}
    <script type="text/javascript">
        django.jQuery(document).on('formset:added', function(event, $row, formsetName) {
            // Row added
        });

        django.jQuery(document).on('formset:removed', function(event, $row, formsetName) {
            // Row removed
        });
    </script>
    {% endblock %}