def media(self): # The media of the inline focuses on the admin settings, # whether to expose the scripts for filter_horizontal etc.. # The admin helper exposes the inline + formset media. base_media = super(PolymorphicInlineModelAdmin, self).media all_media = Media() add_media(all_media, base_media) # Add all media of the child inline instances for child_instance in self.child_inline_instances: child_media = child_instance.media # Avoid adding the same media object again and again if (child_media._css != base_media._css and child_media._js != base_media._js): add_media(all_media, child_media) add_media(all_media, self.polymorphic_media) return all_media
def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.frontend_media except AttributeError: base = ImmutableMedia.empty_instance # Get the media definition for this class definition = getattr(cls, "FrontendMedia", None) if definition: media = Media(definition) # Not supporting extend=('js',) here, not documented in Django either. if getattr(definition, "extend", True) and base is not ImmutableMedia.empty_instance: return base + media return media else: return base
def vendor(*tags): # media = Media() # for tag in tags: # file_type = tag.split('.')[-1] # files = xstatic(tag) # if file_type == 'js': # media.add_js(files) # elif file_type == 'css': # media.add_css({'screen': files}) # return media css = {'screen': []} js = [] for tag in tags: file_type = tag.split('.')[-1] files = xstatic(tag) if file_type == 'js': js.extend(files) elif file_type == 'css': css['screen'] += files return Media(css=css, js=js)
def media(self): media = super(DjangoQLSearchMixin, self).media if self.djangoql_completion: js = [ 'djangoql/js/lib/lexer.js', 'djangoql/js/completion.js', ] if self.search_mode_toggle_enabled(): js.append('djangoql/js/completion_admin_toggle.js') js.append('djangoql/js/completion_admin.js') media += Media( css={ '': ( 'djangoql/css/completion.css', 'djangoql/css/completion_admin.css', ) }, js=js, ) return media
def test_css_packages_with_pipeline_disabled(self): """Testing PipelineFormMedia.css_packages with PIPELINE_ENABLED=False""" class MyMedia(PipelineFormMedia): css_packages = { 'all': ('styles1', 'styles2'), 'print': ('print', ), } css = {'all': ('extra1.css', 'extra2.css')} media = Media(MyMedia) self.assertEqual( MyMedia.css, { 'all': [ 'extra1.css', 'extra2.css', 'pipeline/css/first.css', 'pipeline/css/second.css', 'pipeline/css/unicode.css', ], 'print': ['pipeline/css/urls.css'], }) self.assertEqual(MyMedia.css, media._css) expected_regex = [ '<link href="%s" type="text/css" media="all" ' 'rel="stylesheet"( /)?>' % path for path in ( '/static/extra1.css', '/static/extra2.css', '/static/pipeline/css/first.css', '/static/pipeline/css/second.css', '/static/pipeline/css/unicode.css', ) ] + [ '<link href="/static/pipeline/css/urls.css" type="text/css" ' 'media="print" rel="stylesheet"( /)?>' ] for rendered_node, expected_node in zip(media.render_css(), expected_regex): self.assertRegex(rendered_node, expected_node)
def _media(self): """ The medias needed to enhance the admin page. """ def static_url(url): return staticfiles_storage.url('zinnia_markitup/%s' % url) media = super(EntryAdminMarkItUpMixin, self).media media += Media(js=(static_url('js/jquery.min.js'), static_url('js/markitup/jquery.markitup.js'), static_url('js/markitup/sets/%s/set.js' % (settings.MARKUP_LANGUAGE)), reverse('admin:zinnia_entry_markitup')), css={ 'all': (static_url('js/markitup/skins/django/style.css'), static_url('js/markitup/sets/%s/style.css' % (settings.MARKUP_LANGUAGE))) }) return media
def _media(self): # 修改font-awesome, jq为国内地址 css = { 'all': ('https://cdn.staticfile.org/font-awesome/4.4.0/css/font-awesome.min.css', 'froala_editor/css/froala_editor.min.css', 'froala_editor/css/froala_style.min.css', 'froala_editor/css/froala-django.css') } js = ( 'froala_editor/js/froala_editor.min.js', 'froala_editor/js/froala-django.js', ) if self.include_jquery: js = ('https://cdn.staticfile.org/jquery/1.11.0/jquery.min.js', ) + js if self.theme: css['all'] += ('froala_editor/css/themes/' + self.theme + '.min.css', ) if self.language: js += ('froala_editor/js/languages/' + self.language + '.js', ) for plugin in self.plugins: js += ('froala_editor/js/plugins/' + plugin + '.min.js', ) from froala_editor import PLUGINS_WITH_CSS if plugin in PLUGINS_WITH_CSS: css['all'] += ('froala_editor/css/plugins/' + plugin + '.min.css', ) for plugin in self.third_party: js += ('froala_editor/js/third_party/' + plugin + '.min.js', ) from froala_editor import THIRD_PARTY_WITH_CSS if plugin in THIRD_PARTY_WITH_CSS: css['all'] += ('froala_editor/css/third_party/' + plugin + '.min.css', ) return Media(css=css, js=js)
def media(self): js = [static("froala/vendor/js/froala_editor.pkgd.min.js")] css = [ static("froala/css/wagtailfroala.css"), static("froala/vendor/css/froala_editor.pkgd.min.css"), "//cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.css", "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css", ] if getattr(settings, "FROALA_CODEMIRROR", True): js.append("//cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.js") js.append("//cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/mode/xml/xml.min.js") css.append("//cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.css") # Maintain the order of JavaScript files. js.append(static("froala/js/froala.js")) if getattr(settings, "FROALA_FONT_AWESOME", True): css.append("//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css") return Media(js=js, css={"all": css})
class TimetableWidget(DashboardWidget): template = "chronos/widget.html" def get_context(self, request): from aleksis.apps.chronos.util.build import build_timetable # noqa context = {"has_plan": True} wanted_day = TimePeriod.get_next_relevant_day(timezone.now().date(), datetime.now().time()) if has_person(request.user): person = request.user.person type_ = person.timetable_type # Build timetable timetable = build_timetable("person", person, wanted_day) if type_ is None: # If no student or teacher, redirect to all timetables context["has_plan"] = False else: context["timetable"] = timetable context["holiday"] = Holiday.on_day(wanted_day) context["type"] = type_ context["day"] = wanted_day context["periods"] = TimePeriod.get_times_dict() context["smart"] = True else: context["has_plan"] = False return context media = Media(css={"all": ("css/chronos/timetable.css", )}) class Meta: proxy = True verbose_name = _("Timetable widget") verbose_name_plural = _("Timetable widgets")
def media(self): # Theme and version from Wagtail Code Block settings THEME = get_theme() PRISM_VERSION = get_prism_version() if THEME: prism_theme = '-{theme}'.format(theme=THEME) else: prism_theme = "" js_list = [ "//cdnjs.cloudflare.com/ajax/libs/prism/{prism_version}/prism.min.js" .format(prism_version=PRISM_VERSION, ), ] # Get the languages for the site from Django's settings, or the default in get_language_choices() for lang_code, lang_name in get_language_choices(): if lang_code not in [ included_language[0] for included_language in self.INCLUDED_LANGUAGES ]: js_list.append( "//cdnjs.cloudflare.com/ajax/libs/prism/{prism_version}/components/prism-{lang_code}.min.js" .format( prism_version=PRISM_VERSION, lang_code=lang_code, )) return Media( js=js_list, css={ 'all': [ "//cdnjs.cloudflare.com/ajax/libs/prism/{prism_version}/themes/prism{prism_theme}.min.css" .format( prism_version=PRISM_VERSION, prism_theme=prism_theme, ), "wagtailcodeblock/css/wagtail-code-block.min.css", ] })
def _media(self): css = { 'all': ('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css', 'froala_editor/css/froala_editor.min.css', 'froala_editor/css/froala_style.min.css', 'froala_editor/css/froala-django.css') } js = ('froala_editor/js/froala_editor.min.js', 'froala_editor/js/froala-django.js',) if self.include_jquery: js = ('https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js',) + js if self.theme: css['all'] += ('froala_editor/css/themes/' + self.theme + '.css',) if self.language: js += ('froala_editor/js/languages/' + self.language + '.js',) for plugin in self.plugins: js += ('froala_editor/js/plugins/' + plugin + '.min.js',) if plugin in PLUGINS_WITH_CSS: css['all'] += ('froala_editor/css/plugins/' + plugin + '.min.css',) return Media(css=css, js=js)
def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example. """ html_output = [] merged_media = Media() for contentitem, output in result.get_output(include_exceptions=True): if output is ResultTracker.MISSING: # Likely get_real_instances() didn't return an item for it. # The get_real_instances() didn't return an item for the derived table. This happens when either: # 1. that table is truncated/reset, while there is still an entry in the base ContentItem table. # A query at the derived table happens every time the page is being rendered. # 2. the model was completely removed which means there is also a stale ContentType object. class_name = _get_stale_item_class_name(contentitem) html_output.append(mark_safe(u"<!-- Missing derived model for ContentItem #{id}: {cls}. -->\n".format(id=contentitem.pk, cls=class_name))) logger.warning("Missing derived model for ContentItem #{id}: {cls}.".format(id=contentitem.pk, cls=class_name)) elif isinstance(output, Exception): html_output.append(u'<!-- error: {0} -->\n'.format(str(output))) else: html_output.append(output.html) add_media(merged_media, output.media) return html_output, merged_media
def test_js_packages_with_pipeline_enabled(self): """Testing PipelineFormMedia.js_packages with PIPELINE_ENABLED=True""" class MyMedia(PipelineFormMedia): js_packages = ('scripts1', 'scripts2') js = ('extra1.js', 'extra2.js') media = Media(MyMedia) self.assertEqual(MyMedia.js, [ 'extra1.js', 'extra2.js', '/static/scripts1.min.js', '/static/scripts2.min.js', ]) self.assertEqual(MyMedia.js, media._js) self.assertEqual(media.render_js(), [ '<script type="text/javascript" src="%s"></script>' % path for path in ( '/static/extra1.js', '/static/extra2.js', '/static/scripts1.min.js', '/static/scripts2.min.js', ) ])
def test_asset(self): media = Media( css={"print": ["app/print.css"]}, js=[ "app/test.js", JS("app/asset.js", { "id": "asset-script", "data-the-answer": 42 }), JS("app/asset-without.js", {}), ], ) html = "%s" % media # print(html) self.assertInHTML( '<link href="/static/app/print.css" type="text/css" media="print" rel="stylesheet" />', # noqa html, ) self.assertInHTML( '<script{} src="/static/app/test.js"></script>'.format( JS_TYPE), # noqa html, ) self.assertInHTML( '<script{} src="/static/app/asset.js" data-the-answer="42" id="asset-script"></script>' .format( # noqa JS_TYPE), html, ) self.assertInHTML( '<script{} src="/static/app/asset-without.js"></script>'.format( JS_TYPE), html, )
def media(self): media = Media() for item in self.menu_items: media += item.media return media
def media(self): js = [ static('vendor/ace/ace.js'), static('vendor/ace/utils.js'), ] return Media(js=js)
def media(self): media = Media() for item in self.registered_search_areas: media += item.media return media
def media(self): "Injects OpenLayers jquery into the admin." return super().media + Media(js=[self.openlayers_url] + self.extra_js)
def get_media(self): return super(MaterialCloseBillAdmin, self).get_media() + Media( js=[self.static('/js/materialin.js')])
def get_media(self): return super(BudgetAdmin, self).get_media() + Media( js=[self.static('/js/budget.js')])
def get_media(self, media): media = media + Media( js=["/static/plugins/js/xadmin.plugin.button.js"]) return media
def media(self): media = Media() for item in self.summary_items: media += item.media return media
class PolymorphicInlineModelAdmin(InlineModelAdmin): """ A polymorphic inline, where each formset row can be a different form. Note that: * Permissions are only checked on the base model. * The child inlines can't override the base model fields, only this parent inline can do that. """ formset = BasePolymorphicInlineFormSet #: The extra media to add for the polymorphic inlines effect. #: This can be redefined for subclasses. polymorphic_media = Media( js=( 'polymorphic/js/polymorphic_inlines.js', ), css={ 'all': ( 'polymorphic/css/polymorphic_inlines.css', ) } ) #: The extra forms to show #: By default there are no 'extra' forms as the desired type is unknown. #: Instead, add each new item using JavaScript that first offers a type-selection. extra = 0 #: Inlines for all model sub types that can be displayed in this inline. #: Each row is a :class:`PolymorphicInlineModelAdmin.Child` child_inlines = () def __init__(self, parent_model, admin_site): super(PolymorphicInlineModelAdmin, self).__init__(parent_model, admin_site) # Extra check to avoid confusion # While we could monkeypatch the admin here, better stay explicit. parent_admin = admin_site._registry.get(parent_model, None) if parent_admin is not None: # Can be None during check if not isinstance(parent_admin, PolymorphicInlineSupportMixin): raise ImproperlyConfigured( "To use polymorphic inlines, add the `PolymorphicInlineSupportMixin` mixin " "to the ModelAdmin that hosts the inline." ) # While the inline is created per request, the 'request' object is not known here. # Hence, creating all child inlines unconditionally, without checking permissions. self.child_inline_instances = self.get_child_inline_instances() # Create a lookup table self._child_inlines_lookup = {} for child_inline in self.child_inline_instances: self._child_inlines_lookup[child_inline.model] = child_inline def get_child_inline_instances(self): """ :rtype List[PolymorphicInlineModelAdmin.Child] """ instances = [] for ChildInlineType in self.child_inlines: instances.append(ChildInlineType(parent_inline=self)) return instances def get_child_inline_instance(self, model): """ Find the child inline for a given model. :rtype: PolymorphicInlineModelAdmin.Child """ try: return self._child_inlines_lookup[model] except KeyError: raise ValueError("Model '{0}' not found in child_inlines".format(model.__name__)) def get_formset(self, request, obj=None, **kwargs): """ Construct the inline formset class. This passes all class attributes to the formset. :rtype: type """ # Construct the FormSet class FormSet = super(PolymorphicInlineModelAdmin, self).get_formset(request, obj=obj, **kwargs) # Instead of completely redefining super().get_formset(), we use # the regular inlineformset_factory(), and amend that with our extra bits. # This code line is the essence of what polymorphic_inlineformset_factory() does. FormSet.child_forms = polymorphic_child_forms_factory( formset_children=self.get_formset_children(request, obj=obj) ) return FormSet def get_formset_children(self, request, obj=None): """ The formset 'children' provide the details for all child models that are part of this formset. It provides a stripped version of the modelform/formset factory methods. """ formset_children = [] for child_inline in self.child_inline_instances: # TODO: the children can be limited here per request based on permissions. formset_children.append(child_inline.get_formset_child(request, obj=obj)) return formset_children def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ if self.fieldsets: return self.fieldsets else: return [] # Avoid exposing fields to the child def get_fields(self, request, obj=None): if self.fields: return self.fields else: return [] # Avoid exposing fields to the child @property def media(self): # The media of the inline focuses on the admin settings, # whether to expose the scripts for filter_horizontal etc.. # The admin helper exposes the inline + formset media. base_media = super(PolymorphicInlineModelAdmin, self).media all_media = Media() add_media(all_media, base_media) # Add all media of the child inline instances for child_instance in self.child_inline_instances: child_media = child_instance.media # Avoid adding the same media object again and again if child_media._css != base_media._css and child_media._js != base_media._js: add_media(all_media, child_media) add_media(all_media, self.polymorphic_media) return all_media class Child(InlineModelAdmin): """ The child inline; which allows configuring the admin options for the child appearance. Note that not all options will be honored by the parent, notably the formset options: * :attr:`extra` * :attr:`min_num` * :attr:`max_num` The model form options however, will all be read. """ formset_child = PolymorphicFormSetChild extra = 0 # TODO: currently unused for the children. def __init__(self, parent_inline): self.parent_inline = parent_inline super(PolymorphicInlineModelAdmin.Child, self).__init__(parent_inline.parent_model, parent_inline.admin_site) def get_formset(self, request, obj=None, **kwargs): # The child inline is only used to construct the form, # and allow to override the form field attributes. # The formset is created by the parent inline. raise RuntimeError("The child get_formset() is not used.") def get_fields(self, request, obj=None): if self.fields: return self.fields # Standard Django logic, use the form to determine the fields. # The form needs to pass through all factory logic so all 'excludes' are set as well. # Default Django does: form = self.get_formset(request, obj, fields=None).form # Use 'fields=None' avoids recursion in the field autodetection. form = self.get_formset_child(request, obj, fields=None).get_form() return list(form.base_fields) + list(self.get_readonly_fields(request, obj)) def get_formset_child(self, request, obj=None, **kwargs): """ Return the formset child that the parent inline can use to represent us. :rtype: PolymorphicFormSetChild """ # Similar to the normal get_formset(), the caller may pass fields to override the defaults settings # in the inline. In Django's GenericInlineModelAdmin.get_formset() this is also used in the same way, # to make sure the 'exclude' also contains the GFK fields. # # Hence this code is almost identical to InlineModelAdmin.get_formset() # and GenericInlineModelAdmin.get_formset() # # Transfer the local inline attributes to the formset child, # this allows overriding settings. if 'fields' in kwargs: fields = kwargs.pop('fields') else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) #can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "fields": fields, "exclude": exclude or None, "formfield_callback": partial(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) # This goes through the same logic that get_formset() calls # by passing the inline class attributes to modelform_factory() FormSetChildClass = self.formset_child return FormSetChildClass(self.model, **defaults)
def media(self): return Media( js=[static('wagtailadmin/js/submenu.js')]) + self.menu.media
def media(self): js = [static('js/multiple_select_widget.js')] css = {'all': (static('css/multiple_select_widget.css'), )} return Media(js=js, css=css)
def media(self): media = Media() for item in self.registered_menu_items: media += item.media return media
def get_media(self): return super(MaterialInRecordAdmin, self).get_media() + Media( js=[self.static('/js/materialin.js')])
def get_media(self, media): return media + Media(css={ 'screen': [ self.static('xadmin/css/xadmin.plugin.aggregation.css'), ] })
def media(self): js = [static('fsm/js/fsm.js')] css = {'all': (static('fsm/css/fsm.css'), )} return Media(js=js, css=css)
# Cowbell <https://demozoo.github.io/cowbell/> integration import re from django.contrib.staticfiles.storage import staticfiles_storage from django.forms import Media PLAYERS_BY_FILETYPE = { 'stc': ('Cowbell.Player.ZXSTC', {}, Media(js=[ 'productions/js/cowbell/cowbell.min.js', 'productions/js/cowbell/ay_chip.min.js', 'productions/js/cowbell/zx.min.js' ])), 'pt3': ('Cowbell.Player.ZXPT3', {}, Media(js=[ 'productions/js/cowbell/cowbell.min.js', 'productions/js/cowbell/ay_chip.min.js', 'productions/js/cowbell/zx.min.js' ])), 'vtx': ('Cowbell.Player.VTX', {}, Media(js=[ 'productions/js/cowbell/cowbell.min.js', 'productions/js/cowbell/ay_chip.min.js', 'productions/js/cowbell/vtx.min.js' ])), 'mp3': ('Cowbell.Player.Audio', {}, Media(js=['productions/js/cowbell/cowbell.min.js'])), 'ogg': ('Cowbell.Player.Audio', {}, Media(js=['productions/js/cowbell/cowbell.min.js'])), 'openmpt': ('Cowbell.Player.OpenMPT', {