Kaydet (Commit) 459f7c80 authored tarafından Matthias Kestenholz's avatar Matthias Kestenholz Kaydeden (comit) Tim Graham

[2.2.x] Fixed #30179 -- Fixed form Media merging when pairwise merging is insufficient.

Thanks gasman for the tests, and codingjoe and timgraham for the review.

Backport of 231b5139 from master.
üst 77e53da1
...@@ -6,16 +6,21 @@ import copy ...@@ -6,16 +6,21 @@ import copy
import datetime import datetime
import re import re
import warnings import warnings
from collections import defaultdict
from itertools import chain from itertools import chain
from django.conf import settings from django.conf import settings
from django.forms.utils import to_current_timezone from django.forms.utils import to_current_timezone
from django.templatetags.static import static from django.templatetags.static import static
from django.utils import datetime_safe, formats from django.utils import datetime_safe, formats
from django.utils.datastructures import OrderedSet
from django.utils.dates import MONTHS from django.utils.dates import MONTHS
from django.utils.formats import get_format from django.utils.formats import get_format
from django.utils.html import format_html, html_safe from django.utils.html import format_html, html_safe
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.topological_sort import (
CyclicDependencyError, stable_topological_sort,
)
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from .renderers import get_default_renderer from .renderers import get_default_renderer
...@@ -59,22 +64,15 @@ class Media: ...@@ -59,22 +64,15 @@ class Media:
@property @property
def _css(self): def _css(self):
css = self._css_lists[0] css = defaultdict(list)
# filter(None, ...) avoids calling merge with empty dicts. for css_list in self._css_lists:
for obj in filter(None, self._css_lists[1:]): for medium, sublist in css_list.items():
css = { css[medium].append(sublist)
medium: self.merge(css.get(medium, []), obj.get(medium, [])) return {medium: self.merge(*lists) for medium, lists in css.items()}
for medium in css.keys() | obj.keys()
}
return css
@property @property
def _js(self): def _js(self):
js = self._js_lists[0] return self.merge(*self._js_lists)
# filter(None, ...) avoids calling merge() with empty lists.
for obj in filter(None, self._js_lists[1:]):
js = self.merge(js, obj)
return js
def render(self): def render(self):
return mark_safe('\n'.join(chain.from_iterable(getattr(self, 'render_' + name)() for name in MEDIA_TYPES))) return mark_safe('\n'.join(chain.from_iterable(getattr(self, 'render_' + name)() for name in MEDIA_TYPES)))
...@@ -115,39 +113,37 @@ class Media: ...@@ -115,39 +113,37 @@ class Media:
raise KeyError('Unknown media type "%s"' % name) raise KeyError('Unknown media type "%s"' % name)
@staticmethod @staticmethod
def merge(list_1, list_2): def merge(*lists):
""" """
Merge two lists while trying to keep the relative order of the elements. Merge lists while trying to keep the relative order of the elements.
Warn if the lists have the same two elements in a different relative Warn if the lists have the same elements in a different relative order.
order.
For static assets it can be important to have them included in the DOM For static assets it can be important to have them included in the DOM
in a certain order. In JavaScript you may not be able to reference a in a certain order. In JavaScript you may not be able to reference a
global or in CSS you might want to override a style. global or in CSS you might want to override a style.
""" """
# Start with a copy of list_1. dependency_graph = defaultdict(set)
combined_list = list(list_1) all_items = OrderedSet()
last_insert_index = len(list_1) for list_ in filter(None, lists):
# Walk list_2 in reverse, inserting each element into combined_list if head = list_[0]
# it doesn't already exist. # The first items depend on nothing but have to be part of the
for path in reversed(list_2): # dependency graph to be included in the result.
try: dependency_graph.setdefault(head, set())
# Does path already exist in the list? for item in list_:
index = combined_list.index(path) all_items.add(item)
except ValueError: # No self dependencies
# Add path to combined_list since it doesn't exist. if head != item:
combined_list.insert(last_insert_index, path) dependency_graph[item].add(head)
else: head = item
if index > last_insert_index: try:
warnings.warn( return stable_topological_sort(all_items, dependency_graph)
'Detected duplicate Media files in an opposite order:\n' except CyclicDependencyError:
'%s\n%s' % (combined_list[last_insert_index], combined_list[index]), warnings.warn(
MediaOrderConflictWarning, 'Detected duplicate Media files in an opposite order: {}'.format(
) ', '.join(repr(l) for l in lists)
# path already exists in the list. Update last_insert_index so ), MediaOrderConflictWarning,
# that the following elements are inserted in front of this one. )
last_insert_index = index return list(all_items)
return combined_list
def __add__(self, other): def __add__(self, other):
combined = Media() combined = Media()
......
...@@ -497,10 +497,10 @@ class TestInlineMedia(TestDataMixin, TestCase): ...@@ -497,10 +497,10 @@ class TestInlineMedia(TestDataMixin, TestCase):
response.context['inline_admin_formsets'][0].media._js, response.context['inline_admin_formsets'][0].media._js,
[ [
'admin/js/vendor/jquery/jquery.min.js', 'admin/js/vendor/jquery/jquery.min.js',
'admin/js/jquery.init.js',
'admin/js/inlines.min.js',
'my_awesome_inline_scripts.js', 'my_awesome_inline_scripts.js',
'custom_number.js', 'custom_number.js',
'admin/js/jquery.init.js',
'admin/js/inlines.min.js',
] ]
) )
self.assertContains(response, 'my_awesome_inline_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js')
......
...@@ -139,4 +139,4 @@ class AutocompleteMixinTests(TestCase): ...@@ -139,4 +139,4 @@ class AutocompleteMixinTests(TestCase):
else: else:
expected_files = base_files expected_files = base_files
with translation.override(lang): with translation.override(lang):
self.assertEqual(AutocompleteSelect(rel, admin.site).media._js, expected_files) self.assertEqual(AutocompleteSelect(rel, admin.site).media._js, list(expected_files))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment