About Combined Asset Media

When you have multiple forms or formsets with the same JavaScript widgets, you shouldn't include asset media separately in your template:

1
2
3
{{ form.media }}
{{ formset1.media }}
{{ formset2.media }}

This would duplicate the CSS files and JavaScripts and would cause double initialization of those shared widgets.

Instead, combine the media objects in the view as follows:

1
2
3
4
5
6
context = {
    "form": form,
    "formset1": formset1,
    "formset2": formset2,
    "combined_media": form.media + formset1.media + formset2.media,
}

and use the combined media in the template:

1
{{ combined_media }}

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 Django 2.2