From ef6502060d193917e0e70b78049d8104ccad46fd Mon Sep 17 00:00:00 2001
From: dmpayton <derek.payton@gmail.com>
Date: Tue, 20 Nov 2012 15:34:44 -0800
Subject: [PATCH 1/2] Allow inline JS/CSS in forms.Media (#13978)

---
 django/forms/widgets.py                    |   44 ++++++++++++++++++++--------
 docs/topics/forms/media.txt                |   37 +++++++++++++++++++++++
 tests/regressiontests/forms/tests/media.py |   37 +++++++++++++++++++++++
 3 files changed, 106 insertions(+), 12 deletions(-)

diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index c761ea8..65e59e2 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -34,6 +34,16 @@
 
 @python_2_unicode_compatible
 class Media(object):
+    class Inline(object):
+        def __init__(self, content):
+            self.content = content
+
+        def __eq__(self, other):
+            return (
+                type(self) is type(other) and
+                self.content == other.content
+            )
+
     def __init__(self, media=None, **kwargs):
         if media:
             media_attrs = media.__dict__
@@ -57,16 +67,26 @@ def render(self):
         return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
 
     def render_js(self):
-        return [format_html('<script type="text/javascript" src="{0}"></script>', self.absolute_path(path)) for path in self._js]
+        html = []
+        for script in self._js:
+            if isinstance(script, self.Inline):
+                html.append(format_html('<script type="text/javascript">{0}</script>', mark_safe(script.content)))
+            else:
+                html.append(format_html('<script type="text/javascript" src="{0}"></script>', self.absolute_path(script)))
+        return html
 
     def render_css(self):
         # To keep rendering order consistent, we can't just iterate over items().
         # We need to sort the keys, and iterate over the sorted list.
+        html = []
         media = sorted(self._css.keys())
-        return chain(*[
-                [format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(path), medium)
-                    for path in self._css[medium]]
-                for medium in media])
+        for medium in media:
+            for style in self._css[medium]:
+                if isinstance(style, self.Inline):
+                    html.append(format_html('<style type="text/css" media="{0}">{1}</style>', medium, mark_safe(style.content)))
+                else:
+                    html.append(format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(style), medium))
+        return html
 
     def absolute_path(self, path, prefix=None):
         if path.startswith(('http://', 'https://', '/')):
@@ -87,16 +107,16 @@ def __getitem__(self, name):
 
     def add_js(self, data):
         if data:
-            for path in data:
-                if path not in self._js:
-                    self._js.append(path)
+            for script in data:
+                if script not in self._js:
+                    self._js.append(script)
 
     def add_css(self, data):
         if data:
-            for medium, paths in data.items():
-                for path in paths:
-                    if not self._css.get(medium) or path not in self._css[medium]:
-                        self._css.setdefault(medium, []).append(path)
+            for medium, styles in data.items():
+                for style in styles:
+                    if not self._css.get(medium) or style not in self._css[medium]:
+                        self._css.setdefault(medium, []).append(style)
 
     def __add__(self, other):
         combined = Media()
diff --git a/docs/topics/forms/media.txt b/docs/topics/forms/media.txt
index 98e70e5..34d5f89 100644
--- a/docs/topics/forms/media.txt
+++ b/docs/topics/forms/media.txt
@@ -167,6 +167,43 @@ If you require even more control over media inheritance, define your media
 using a :ref:`dynamic property <dynamic-property>`. Dynamic properties give
 you complete control over which media files are inherited, and which are not.
 
+Specifying inline media
+-----------------------
+
+.. versionadded:: 1.5
+
+At some point you may run into a situation that calls for a bit of inline CSS
+or JavaScript, such as initializing a JavaScript plugin. To do this, simply
+pass your inline code as a ``forms.Media.Inline`` object in the Media class::
+
+    >>> class FancyCalendarWidget(CalendarWidget):
+    ...     class Media:
+    ...         css = {
+    ...             'all': ('fancy.css',)
+    ...         }
+    ...         js = (
+    ...             'whizbang.js',
+    ...             forms.Media.Inline('init_fancification();'),
+    ...         )
+
+    >>> w = FancyCalendarWidget()
+    >>> print(w.media)
+    <link href="/static/fancy.css" type="text/css" media="all" rel="stylesheet" />
+    <script type="text/javascript" src="/static/whizbang.js"></script>
+    <script type="text/javascript">init_fancification();</script>
+
+Inline CSS works the same way::
+
+    >>> class HoneypotWidget(forms.TextInput):
+    ...     class Media:
+    ...         css = {
+    ...             'all': (forms.Media.Inline(".honeypot_row { display: none; }"),)
+    ...         }
+
+    >>> w = HoneypotWidget()
+    >>> print(w.media)
+    <style type="text/css" media="all">.honeypot_row { display: none; }</style>
+
 .. _dynamic-property:
 
 Media as a dynamic property
diff --git a/tests/regressiontests/forms/tests/media.py b/tests/regressiontests/forms/tests/media.py
index c492a1e..71e969e 100644
--- a/tests/regressiontests/forms/tests/media.py
+++ b/tests/regressiontests/forms/tests/media.py
@@ -455,6 +455,43 @@ class Media:
 <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
 <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
 
+    def test_inline_media(self):
+        ## Inline JavaScript and CSS
+        class MyWidget(TextInput):
+            class Media:
+                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
+                js = (Media.Inline('init_mywidget();'),)
+
+        w = MyWidget()
+        self.assertEqual('<style type="text/css" media="all">.mywidget { display: none; }</style>', str(w.media['css']))
+        self.assertEqual('<script type="text/javascript">init_mywidget();</script>', str(w.media['js']))
+
+    def test_inline_media_property(self):
+        ## Inline JavaScript and CSS as a media property
+        class MyWidget(TextInput):
+            def _media(self):
+                return Media(css={'all': (Media.Inline('.mywidget { display: none; }'),)},
+                             js=(Media.Inline('init_mywidget();'),))
+            media = property(_media)
+
+        w = MyWidget()
+        self.assertEqual('<style type="text/css" media="all">.mywidget { display: none; }</style>', str(w.media['css']))
+        self.assertEqual('<script type="text/javascript">init_mywidget();</script>', str(w.media['js']))
+
+    def test_inline_media_mutiple(self):
+        ## Multiple instances of inline media should only be rendered once
+        class MyWidget(TextInput):
+            class Media:
+                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
+                js = (Media.Inline('init_mywidget();'),)
+
+        class MyForm(Form):
+            field1 = CharField(widget=MyWidget)
+            field2 = CharField(widget=MyWidget)
+
+        f = MyForm()
+        self.assertEqual("""<style type="text/css" media="all">.mywidget { display: none; }</style>
+<script type="text/javascript">init_mywidget();</script>""", str(f.media))
 
 @override_settings(
     STATIC_URL='http://media.example.com/static/',
-- 
1.7.10


From 92850ae865d2c2633a59f19fa77d713e5ed24464 Mon Sep 17 00:00:00 2001
From: dmpayton <derek.payton@gmail.com>
Date: Tue, 27 Nov 2012 18:54:37 -0800
Subject: [PATCH 2/2] Updates for inline media (based on feedback in #13978):
 - Nuke Media.Inline in favor of separate top-level
 classes for JS and CSS - Switch naming from "inline" to
 "internal" (vs. an external script or stylesheet) -
 Update docs and tests to reflect changes

---
 django/forms/widgets.py                    |   50 +++++++++++++++++-----------
 docs/topics/forms/media.txt                |   17 +++++-----
 tests/regressiontests/forms/tests/media.py |   14 ++++----
 3 files changed, 47 insertions(+), 34 deletions(-)

diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index 65e59e2..a925165 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -22,28 +22,40 @@
 from django.utils import datetime_safe, formats, six
 
 __all__ = (
-    'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'PasswordInput',
-    'HiddenInput', 'MultipleHiddenInput', 'ClearableFileInput',
-    'FileInput', 'DateInput', 'DateTimeInput', 'TimeInput', 'Textarea', 'CheckboxInput',
-    'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect',
-    'CheckboxSelectMultiple', 'MultiWidget',
+    'InternalCSS', 'InternalJS', 'Media', 'MediaDefiningClass', 'Widget',
+    'TextInput', 'PasswordInput', 'HiddenInput', 'MultipleHiddenInput',
+    'ClearableFileInput', 'FileInput', 'DateInput', 'DateTimeInput',
+    'TimeInput', 'Textarea', 'CheckboxInput', 'Select', 'NullBooleanSelect',
+    'SelectMultiple', 'RadioSelect', 'CheckboxSelectMultiple', 'MultiWidget',
     'SplitDateTimeWidget',
 )
 
 MEDIA_TYPES = ('css','js')
 
-@python_2_unicode_compatible
-class Media(object):
-    class Inline(object):
-        def __init__(self, content):
-            self.content = content
+class InternalMedia(object):
+    """
+    Base class for specifying internal CSS and JS documents in a Media class.
+    """
+    def __init__(self, content):
+        self.content = content
+
+    def __eq__(self, other):
+        return (
+            type(self) is type(other) and
+            self.content == other.content
+        )
 
-        def __eq__(self, other):
-            return (
-                type(self) is type(other) and
-                self.content == other.content
-            )
+class InternalCSS(InternalMedia):
+    def render(self, medium=None):
+        medium = medium or 'all'
+        return format_html('<style type="text/css" media="{0}">{1}</style>', medium, mark_safe(self.content))
 
+class InternalJS(InternalMedia):
+    def render(self):
+        return format_html('<script type="text/javascript">{0}</script>', mark_safe(self.content))
+
+@python_2_unicode_compatible
+class Media(object):
     def __init__(self, media=None, **kwargs):
         if media:
             media_attrs = media.__dict__
@@ -69,8 +81,8 @@ def render(self):
     def render_js(self):
         html = []
         for script in self._js:
-            if isinstance(script, self.Inline):
-                html.append(format_html('<script type="text/javascript">{0}</script>', mark_safe(script.content)))
+            if isinstance(script, InternalJS):
+                html.append(script.render())
             else:
                 html.append(format_html('<script type="text/javascript" src="{0}"></script>', self.absolute_path(script)))
         return html
@@ -82,8 +94,8 @@ def render_css(self):
         media = sorted(self._css.keys())
         for medium in media:
             for style in self._css[medium]:
-                if isinstance(style, self.Inline):
-                    html.append(format_html('<style type="text/css" media="{0}">{1}</style>', medium, mark_safe(style.content)))
+                if isinstance(style, InternalCSS):
+                    html.append(style.render(medium))
                 else:
                     html.append(format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(style), medium))
         return html
diff --git a/docs/topics/forms/media.txt b/docs/topics/forms/media.txt
index 34d5f89..1e607ce 100644
--- a/docs/topics/forms/media.txt
+++ b/docs/topics/forms/media.txt
@@ -167,14 +167,14 @@ If you require even more control over media inheritance, define your media
 using a :ref:`dynamic property <dynamic-property>`. Dynamic properties give
 you complete control over which media files are inherited, and which are not.
 
-Specifying inline media
------------------------
+Specifying internal media
+-------------------------
 
 .. versionadded:: 1.5
 
-At some point you may run into a situation that calls for a bit of inline CSS
-or JavaScript, such as initializing a JavaScript plugin. To do this, simply
-pass your inline code as a ``forms.Media.Inline`` object in the Media class::
+At some point you may run into a situation that calls for internal CSS
+or JavaScript, perhaps to initialize a plugin. This can be accomplished with
+``InternalCSS`` and ``InternalJS``::
 
     >>> class FancyCalendarWidget(CalendarWidget):
     ...     class Media:
@@ -183,7 +183,7 @@ pass your inline code as a ``forms.Media.Inline`` object in the Media class::
     ...         }
     ...         js = (
     ...             'whizbang.js',
-    ...             forms.Media.Inline('init_fancification();'),
+    ...             forms.InternalJS('init_fancification();'),
     ...         )
 
     >>> w = FancyCalendarWidget()
@@ -192,18 +192,19 @@ pass your inline code as a ``forms.Media.Inline`` object in the Media class::
     <script type="text/javascript" src="/static/whizbang.js"></script>
     <script type="text/javascript">init_fancification();</script>
 
-Inline CSS works the same way::
+Internal CSS is rendered with the correct ``media`` attribute::
 
     >>> class HoneypotWidget(forms.TextInput):
     ...     class Media:
     ...         css = {
-    ...             'all': (forms.Media.Inline(".honeypot_row { display: none; }"),)
+    ...             'all': (forms.InternalCSS(".honeypot_row { display: none; }"),)
     ...         }
 
     >>> w = HoneypotWidget()
     >>> print(w.media)
     <style type="text/css" media="all">.honeypot_row { display: none; }</style>
 
+
 .. _dynamic-property:
 
 Media as a dynamic property
diff --git a/tests/regressiontests/forms/tests/media.py b/tests/regressiontests/forms/tests/media.py
index 71e969e..887e24c 100644
--- a/tests/regressiontests/forms/tests/media.py
+++ b/tests/regressiontests/forms/tests/media.py
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget
+from django.forms import TextInput, InternalCSS, InternalJS, Media, TextInput, CharField, Form, MultiWidget
 from django.template import Template, Context
 from django.test import TestCase
 from django.test.utils import override_settings
@@ -459,8 +459,8 @@ def test_inline_media(self):
         ## Inline JavaScript and CSS
         class MyWidget(TextInput):
             class Media:
-                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
-                js = (Media.Inline('init_mywidget();'),)
+                css = {'all': (InternalCSS('.mywidget { display: none; }'),)}
+                js = (InternalJS('init_mywidget();'),)
 
         w = MyWidget()
         self.assertEqual('<style type="text/css" media="all">.mywidget { display: none; }</style>', str(w.media['css']))
@@ -470,8 +470,8 @@ def test_inline_media_property(self):
         ## Inline JavaScript and CSS as a media property
         class MyWidget(TextInput):
             def _media(self):
-                return Media(css={'all': (Media.Inline('.mywidget { display: none; }'),)},
-                             js=(Media.Inline('init_mywidget();'),))
+                return Media(css={'all': (InternalCSS('.mywidget { display: none; }'),)},
+                             js=(InternalJS('init_mywidget();'),))
             media = property(_media)
 
         w = MyWidget()
@@ -482,8 +482,8 @@ def test_inline_media_mutiple(self):
         ## Multiple instances of inline media should only be rendered once
         class MyWidget(TextInput):
             class Media:
-                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
-                js = (Media.Inline('init_mywidget();'),)
+                css = {'all': (InternalCSS('.mywidget { display: none; }'),)}
+                js = (InternalJS('init_mywidget();'),)
 
         class MyForm(Form):
             field1 = CharField(widget=MyWidget)
-- 
1.7.10

