• 3.2
  • 5.0
  • 6.1
  • Версия документации: 3.1

Настройки JavaScript в админке

События встроенной формы

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 django.jQuery namespace.

В вашем пользовательском шаблоне change_form.html расширьте блок admin_change_form_document_ready и добавьте код прослушивателя событий:

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

{% block admin_change_form_document_ready %}
{{ block.super }}
<script src="{% static 'app/formset_handlers.js' %}"></script>
{% endblock %}
app/static/app/formset_handlers.js
(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);

Два момента, которые следует иметь в виду:

  • Код JavaScript должен находиться в блоке шаблона, если вы наследуете admin/change_form.html, иначе он не будет отображаться в окончательном HTML.

  • {{block.super }} добавлен, потому что блок Django admin_change_form_document_ready содержит код JavaScript для обработки различных операций в форме изменения, и нам нужно, чтобы он тоже отображался.

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

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

{% block admin_change_form_document_ready %}
{{ block.super }}
<script src="{% static 'app/unregistered_handlers.js' %}"></script>
{% endblock %}
app/static/app/unregistered_handlers.js
django.jQuery(document).on('formset:added', function(event, $row, formsetName) {
    // Row added
});

django.jQuery(document).on('formset:removed', function(event, $row, formsetName) {
    // Row removed
});
Back to Top