We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
manage.py compress errors with empty db
In 1.1rc1 manage.py command 'compress' doesn't work anymore if the database isn't migrated yet. I need to be able to do this since i'm running django compress during a docker build.

Complete stacktrace is:

```
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate
    app_config.ready()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/apps.py", line 15, in ready
    dt_settings.patch_all()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/settings.py", line 232, in patch_all
    patch_root_urlconf()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/settings.py", line 220, in patch_root_urlconf
    reverse('djdt:render_panel')
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 550, in reverse
    app_list = resolver.app_dict[ns]
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 352, in app_dict
    self._populate()
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 285, in _populate
    for pattern in reversed(self.url_patterns):
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 402, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 396, in urlconf_module
    self._urlconf_module = import_module(self.urlconf_name)
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/mvantellingen/projects/myorg/myproj/src/myproj/urls.py", line 7, in <module>
    from wagtail.wagtailadmin import urls as wagtailadmin_urls
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py", line 7, in <module>
    from wagtail.wagtailadmin.views import account, chooser, home, pages, tags, userbar
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/views/account.py", line 12, in <module>
    from wagtail.wagtailusers.forms import NotificationPreferencesForm
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailusers/forms.py", line 236, in <module>
    class GroupPagePermissionForm(forms.ModelForm):
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailusers/forms.py", line 238, in GroupPagePermissionForm
    widget=AdminPageChooser(show_edit_link=False))
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/widgets.py", line 123, in __init__
    self.target_content_types = content_type or ContentType.objects.get_for_model(Page)
  File "/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 78, in get_for_model
    "Error creating new content types. Please make sure contenttypes "
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `wagtail/wagtailadmin/widgets.py`
Content:
```
1 from __future__ import absolute_import, unicode_literals
2 
3 import json
4 
5 from django.core.urlresolvers import reverse
6 from django.forms import widgets
7 from django.contrib.contenttypes.models import ContentType
8 from django.utils.translation import ugettext_lazy as _
9 from django.template.loader import render_to_string
10 
11 from wagtail.utils.widgets import WidgetWithScript
12 from wagtail.wagtailcore.models import Page
13 
14 from taggit.forms import TagWidget
15 
16 
17 class AdminAutoHeightTextInput(WidgetWithScript, widgets.Textarea):
18     def __init__(self, attrs=None):
19         # Use more appropriate rows default, given autoheight will alter this anyway
20         default_attrs = {'rows': '1'}
21         if attrs:
22             default_attrs.update(attrs)
23 
24         super(AdminAutoHeightTextInput, self).__init__(default_attrs)
25 
26     def render_js_init(self, id_, name, value):
27         return 'autosize($("#{0}"));'.format(id_)
28 
29 class AdminDateInput(WidgetWithScript, widgets.DateInput):
30     # Set a default date format to match the one that our JS date picker expects -
31     # it can still be overridden explicitly, but this way it won't be affected by
32     # the DATE_INPUT_FORMATS setting
33     def __init__(self, attrs=None, format='%Y-%m-%d'):
34         super(AdminDateInput, self).__init__(attrs=attrs, format=format)
35 
36     def render_js_init(self, id_, name, value):
37         return 'initDateChooser({0});'.format(json.dumps(id_))
38 
39 
40 class AdminTimeInput(WidgetWithScript, widgets.TimeInput):
41     def __init__(self, attrs=None, format='%H:%M'):
42         super(AdminTimeInput, self).__init__(attrs=attrs, format=format)
43 
44     def render_js_init(self, id_, name, value):
45         return 'initTimeChooser({0});'.format(json.dumps(id_))
46 
47 
48 class AdminDateTimeInput(WidgetWithScript, widgets.DateTimeInput):
49     def __init__(self, attrs=None, format='%Y-%m-%d %H:%M'):
50         super(AdminDateTimeInput, self).__init__(attrs=attrs, format=format)
51 
52     def render_js_init(self, id_, name, value):
53         return 'initDateTimeChooser({0});'.format(json.dumps(id_))
54 
55 
56 class AdminTagWidget(WidgetWithScript, TagWidget):
57     def render_js_init(self, id_, name, value):
58         return "initTagField({0}, {1});".format(
59             json.dumps(id_),
60             json.dumps(reverse('wagtailadmin_tag_autocomplete')))
61 
62 
63 class AdminChooser(WidgetWithScript, widgets.Input):
64     input_type = 'hidden'
65     choose_one_text = _("Choose an item")
66     choose_another_text = _("Choose another item")
67     clear_choice_text = _("Clear choice")
68     link_to_chosen_text = _("Edit this item")
69     show_edit_link = True
70 
71     def get_instance(self, model_class, value):
72         # helper method for cleanly turning 'value' into an instance object
73         if value is None:
74             return None
75 
76         try:
77             return model_class.objects.get(pk=value)
78         except model_class.DoesNotExist:
79             return None
80 
81     def get_instance_and_id(self, model_class, value):
82         if value is None:
83             return (None, None)
84         elif isinstance(value, model_class):
85             return (value, value.pk)
86         else:
87             try:
88                 return (model_class.objects.get(pk=value), value)
89             except model_class.DoesNotExist:
90                 return (None, None)
91 
92     def value_from_datadict(self, data, files, name):
93         # treat the empty string as None
94         result = super(AdminChooser, self).value_from_datadict(data, files, name)
95         if result == '':
96             return None
97         else:
98             return result
99 
100     def __init__(self, **kwargs):
101         # allow choose_one_text / choose_another_text to be overridden per-instance
102         if 'choose_one_text' in kwargs:
103             self.choose_one_text = kwargs.pop('choose_one_text')
104         if 'choose_another_text' in kwargs:
105             self.choose_another_text = kwargs.pop('choose_another_text')
106         if 'clear_choice_text' in kwargs:
107             self.clear_choice_text = kwargs.pop('clear_choice_text')
108         if 'link_to_chosen_text' in kwargs:
109             self.link_to_chosen_text = kwargs.pop('link_to_chosen_text')
110         if 'show_edit_link' in kwargs:
111             self.show_edit_link = kwargs.pop('show_edit_link')
112         super(AdminChooser, self).__init__(**kwargs)
113 
114 
115 class AdminPageChooser(AdminChooser):
116     choose_one_text = _('Choose a page')
117     choose_another_text = _('Choose another page')
118     link_to_chosen_text = _('Edit this page')
119 
120     def __init__(self, content_type=None, **kwargs):
121         super(AdminPageChooser, self).__init__(**kwargs)
122 
123         self.target_content_types = content_type or ContentType.objects.get_for_model(Page)
124         # Make sure target_content_types is a list or tuple
125         if not isinstance(self.target_content_types, (list, tuple)):
126             self.target_content_types = [self.target_content_types]
127 
128     def render_html(self, name, value, attrs):
129         if len(self.target_content_types) == 1:
130             model_class = self.target_content_types[0].model_class()
131         else:
132             model_class = Page
133 
134         instance, value = self.get_instance_and_id(model_class, value)
135 
136         original_field_html = super(AdminPageChooser, self).render_html(name, value, attrs)
137 
138         return render_to_string("wagtailadmin/widgets/page_chooser.html", {
139             'widget': self,
140             'original_field_html': original_field_html,
141             'attrs': attrs,
142             'value': value,
143             'page': instance,
144         })
145 
146     def render_js_init(self, id_, name, value):
147         if isinstance(value, Page):
148             page = value
149         else:
150             # Value is an ID look up object
151             if len(self.target_content_types) == 1:
152                 model_class = self.target_content_types[0].model_class()
153             else:
154                 model_class = Page
155 
156             page = self.get_instance(model_class, value)
157 
158         parent = page.get_parent() if page else None
159 
160         return "createPageChooser({id}, {content_type}, {parent});".format(
161             id=json.dumps(id_),
162             content_type=json.dumps([
163                 '{app}.{model}'.format(
164                     app=content_type.app_label,
165                     model=content_type.model)
166                 for content_type in self.target_content_types
167             ]),
168             parent=json.dumps(parent.id if parent else None))
169
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/wagtail/wagtailadmin/widgets.py b/wagtail/wagtailadmin/widgets.py
--- a/wagtail/wagtailadmin/widgets.py
+++ b/wagtail/wagtailadmin/widgets.py
@@ -5,6 +5,7 @@
 from django.core.urlresolvers import reverse
 from django.forms import widgets
 from django.contrib.contenttypes.models import ContentType
+from django.utils.functional import cached_property
 from django.utils.translation import ugettext_lazy as _
 from django.template.loader import render_to_string
 
@@ -119,11 +120,15 @@
 
     def __init__(self, content_type=None, **kwargs):
         super(AdminPageChooser, self).__init__(**kwargs)
+        self._content_type = content_type
 
-        self.target_content_types = content_type or ContentType.objects.get_for_model(Page)
+    @cached_property
+    def target_content_types(self):
+        target_content_types = self._content_type or ContentType.objects.get_for_model(Page)
         # Make sure target_content_types is a list or tuple
-        if not isinstance(self.target_content_types, (list, tuple)):
-            self.target_content_types = [self.target_content_types]
+        if not isinstance(target_content_types, (list, tuple)):
+            target_content_types = [target_content_types]
+        return target_content_types
 
     def render_html(self, name, value, attrs):
         if len(self.target_content_types) == 1:

{"golden_diff": "diff --git a/wagtail/wagtailadmin/widgets.py b/wagtail/wagtailadmin/widgets.py\n--- a/wagtail/wagtailadmin/widgets.py\n+++ b/wagtail/wagtailadmin/widgets.py\n@@ -5,6 +5,7 @@\n from django.core.urlresolvers import reverse\n from django.forms import widgets\n from django.contrib.contenttypes.models import ContentType\n+from django.utils.functional import cached_property\n from django.utils.translation import ugettext_lazy as _\n from django.template.loader import render_to_string\n \n@@ -119,11 +120,15 @@\n \n     def __init__(self, content_type=None, **kwargs):\n         super(AdminPageChooser, self).__init__(**kwargs)\n+        self._content_type = content_type\n \n-        self.target_content_types = content_type or ContentType.objects.get_for_model(Page)\n+    @cached_property\n+    def target_content_types(self):\n+        target_content_types = self._content_type or ContentType.objects.get_for_model(Page)\n         # Make sure target_content_types is a list or tuple\n-        if not isinstance(self.target_content_types, (list, tuple)):\n-            self.target_content_types = [self.target_content_types]\n+        if not isinstance(target_content_types, (list, tuple)):\n+            target_content_types = [target_content_types]\n+        return target_content_types\n \n     def render_html(self, name, value, attrs):\n         if len(self.target_content_types) == 1:\n", "issue": "manage.py compress errors with empty db\nIn 1.1rc1 manage.py command 'compress' doesn't work anymore if the database isn't migrated yet. I need to be able to do this since i'm running django compress during a docker build.\n\nComplete stacktrace is:\n\n```\nTraceback (most recent call last):\n  File \"./manage.py\", line 10, in <module>\n    execute_from_command_line(sys.argv)\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/management/__init__.py\", line 338, in execute_from_command_line\n    utility.execute()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/management/__init__.py\", line 312, in execute\n    django.setup()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/__init__.py\", line 18, in setup\n    apps.populate(settings.INSTALLED_APPS)\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/apps/registry.py\", line 115, in populate\n    app_config.ready()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/apps.py\", line 15, in ready\n    dt_settings.patch_all()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/settings.py\", line 232, in patch_all\n    patch_root_urlconf()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/debug_toolbar/settings.py\", line 220, in patch_root_urlconf\n    reverse('djdt:render_panel')\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py\", line 550, in reverse\n    app_list = resolver.app_dict[ns]\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py\", line 352, in app_dict\n    self._populate()\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py\", line 285, in _populate\n    for pattern in reversed(self.url_patterns):\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py\", line 402, in url_patterns\n    patterns = getattr(self.urlconf_module, \"urlpatterns\", self.urlconf_module)\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/core/urlresolvers.py\", line 396, in urlconf_module\n    self._urlconf_module = import_module(self.urlconf_name)\n  File \"/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py\", line 37, in import_module\n    __import__(name)\n  File \"/Users/mvantellingen/projects/myorg/myproj/src/myproj/urls.py\", line 7, in <module>\n    from wagtail.wagtailadmin import urls as wagtailadmin_urls\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py\", line 7, in <module>\n    from wagtail.wagtailadmin.views import account, chooser, home, pages, tags, userbar\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/views/account.py\", line 12, in <module>\n    from wagtail.wagtailusers.forms import NotificationPreferencesForm\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailusers/forms.py\", line 236, in <module>\n    class GroupPagePermissionForm(forms.ModelForm):\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailusers/forms.py\", line 238, in GroupPagePermissionForm\n    widget=AdminPageChooser(show_edit_link=False))\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/wagtail/wagtailadmin/widgets.py\", line 123, in __init__\n    self.target_content_types = content_type or ContentType.objects.get_for_model(Page)\n  File \"/usr/local/opt/pyenv/versions/myproj/lib/python2.7/site-packages/django/contrib/contenttypes/models.py\", line 78, in get_for_model\n    \"Error creating new content types. Please make sure contenttypes \"\nRuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import, unicode_literals\n\nimport json\n\nfrom django.core.urlresolvers import reverse\nfrom django.forms import widgets\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.loader import render_to_string\n\nfrom wagtail.utils.widgets import WidgetWithScript\nfrom wagtail.wagtailcore.models import Page\n\nfrom taggit.forms import TagWidget\n\n\nclass AdminAutoHeightTextInput(WidgetWithScript, widgets.Textarea):\n    def __init__(self, attrs=None):\n        # Use more appropriate rows default, given autoheight will alter this anyway\n        default_attrs = {'rows': '1'}\n        if attrs:\n            default_attrs.update(attrs)\n\n        super(AdminAutoHeightTextInput, self).__init__(default_attrs)\n\n    def render_js_init(self, id_, name, value):\n        return 'autosize($(\"#{0}\"));'.format(id_)\n\nclass AdminDateInput(WidgetWithScript, widgets.DateInput):\n    # Set a default date format to match the one that our JS date picker expects -\n    # it can still be overridden explicitly, but this way it won't be affected by\n    # the DATE_INPUT_FORMATS setting\n    def __init__(self, attrs=None, format='%Y-%m-%d'):\n        super(AdminDateInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initDateChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminTimeInput(WidgetWithScript, widgets.TimeInput):\n    def __init__(self, attrs=None, format='%H:%M'):\n        super(AdminTimeInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initTimeChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminDateTimeInput(WidgetWithScript, widgets.DateTimeInput):\n    def __init__(self, attrs=None, format='%Y-%m-%d %H:%M'):\n        super(AdminDateTimeInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initDateTimeChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminTagWidget(WidgetWithScript, TagWidget):\n    def render_js_init(self, id_, name, value):\n        return \"initTagField({0}, {1});\".format(\n            json.dumps(id_),\n            json.dumps(reverse('wagtailadmin_tag_autocomplete')))\n\n\nclass AdminChooser(WidgetWithScript, widgets.Input):\n    input_type = 'hidden'\n    choose_one_text = _(\"Choose an item\")\n    choose_another_text = _(\"Choose another item\")\n    clear_choice_text = _(\"Clear choice\")\n    link_to_chosen_text = _(\"Edit this item\")\n    show_edit_link = True\n\n    def get_instance(self, model_class, value):\n        # helper method for cleanly turning 'value' into an instance object\n        if value is None:\n            return None\n\n        try:\n            return model_class.objects.get(pk=value)\n        except model_class.DoesNotExist:\n            return None\n\n    def get_instance_and_id(self, model_class, value):\n        if value is None:\n            return (None, None)\n        elif isinstance(value, model_class):\n            return (value, value.pk)\n        else:\n            try:\n                return (model_class.objects.get(pk=value), value)\n            except model_class.DoesNotExist:\n                return (None, None)\n\n    def value_from_datadict(self, data, files, name):\n        # treat the empty string as None\n        result = super(AdminChooser, self).value_from_datadict(data, files, name)\n        if result == '':\n            return None\n        else:\n            return result\n\n    def __init__(self, **kwargs):\n        # allow choose_one_text / choose_another_text to be overridden per-instance\n        if 'choose_one_text' in kwargs:\n            self.choose_one_text = kwargs.pop('choose_one_text')\n        if 'choose_another_text' in kwargs:\n            self.choose_another_text = kwargs.pop('choose_another_text')\n        if 'clear_choice_text' in kwargs:\n            self.clear_choice_text = kwargs.pop('clear_choice_text')\n        if 'link_to_chosen_text' in kwargs:\n            self.link_to_chosen_text = kwargs.pop('link_to_chosen_text')\n        if 'show_edit_link' in kwargs:\n            self.show_edit_link = kwargs.pop('show_edit_link')\n        super(AdminChooser, self).__init__(**kwargs)\n\n\nclass AdminPageChooser(AdminChooser):\n    choose_one_text = _('Choose a page')\n    choose_another_text = _('Choose another page')\n    link_to_chosen_text = _('Edit this page')\n\n    def __init__(self, content_type=None, **kwargs):\n        super(AdminPageChooser, self).__init__(**kwargs)\n\n        self.target_content_types = content_type or ContentType.objects.get_for_model(Page)\n        # Make sure target_content_types is a list or tuple\n        if not isinstance(self.target_content_types, (list, tuple)):\n            self.target_content_types = [self.target_content_types]\n\n    def render_html(self, name, value, attrs):\n        if len(self.target_content_types) == 1:\n            model_class = self.target_content_types[0].model_class()\n        else:\n            model_class = Page\n\n        instance, value = self.get_instance_and_id(model_class, value)\n\n        original_field_html = super(AdminPageChooser, self).render_html(name, value, attrs)\n\n        return render_to_string(\"wagtailadmin/widgets/page_chooser.html\", {\n            'widget': self,\n            'original_field_html': original_field_html,\n            'attrs': attrs,\n            'value': value,\n            'page': instance,\n        })\n\n    def render_js_init(self, id_, name, value):\n        if isinstance(value, Page):\n            page = value\n        else:\n            # Value is an ID look up object\n            if len(self.target_content_types) == 1:\n                model_class = self.target_content_types[0].model_class()\n            else:\n                model_class = Page\n\n            page = self.get_instance(model_class, value)\n\n        parent = page.get_parent() if page else None\n\n        return \"createPageChooser({id}, {content_type}, {parent});\".format(\n            id=json.dumps(id_),\n            content_type=json.dumps([\n                '{app}.{model}'.format(\n                    app=content_type.app_label,\n                    model=content_type.model)\n                for content_type in self.target_content_types\n            ]),\n            parent=json.dumps(parent.id if parent else None))\n", "path": "wagtail/wagtailadmin/widgets.py"}], "after_files": [{"content": "from __future__ import absolute_import, unicode_literals\n\nimport json\n\nfrom django.core.urlresolvers import reverse\nfrom django.forms import widgets\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.loader import render_to_string\n\nfrom wagtail.utils.widgets import WidgetWithScript\nfrom wagtail.wagtailcore.models import Page\n\nfrom taggit.forms import TagWidget\n\n\nclass AdminAutoHeightTextInput(WidgetWithScript, widgets.Textarea):\n    def __init__(self, attrs=None):\n        # Use more appropriate rows default, given autoheight will alter this anyway\n        default_attrs = {'rows': '1'}\n        if attrs:\n            default_attrs.update(attrs)\n\n        super(AdminAutoHeightTextInput, self).__init__(default_attrs)\n\n    def render_js_init(self, id_, name, value):\n        return 'autosize($(\"#{0}\"));'.format(id_)\n\nclass AdminDateInput(WidgetWithScript, widgets.DateInput):\n    # Set a default date format to match the one that our JS date picker expects -\n    # it can still be overridden explicitly, but this way it won't be affected by\n    # the DATE_INPUT_FORMATS setting\n    def __init__(self, attrs=None, format='%Y-%m-%d'):\n        super(AdminDateInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initDateChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminTimeInput(WidgetWithScript, widgets.TimeInput):\n    def __init__(self, attrs=None, format='%H:%M'):\n        super(AdminTimeInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initTimeChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminDateTimeInput(WidgetWithScript, widgets.DateTimeInput):\n    def __init__(self, attrs=None, format='%Y-%m-%d %H:%M'):\n        super(AdminDateTimeInput, self).__init__(attrs=attrs, format=format)\n\n    def render_js_init(self, id_, name, value):\n        return 'initDateTimeChooser({0});'.format(json.dumps(id_))\n\n\nclass AdminTagWidget(WidgetWithScript, TagWidget):\n    def render_js_init(self, id_, name, value):\n        return \"initTagField({0}, {1});\".format(\n            json.dumps(id_),\n            json.dumps(reverse('wagtailadmin_tag_autocomplete')))\n\n\nclass AdminChooser(WidgetWithScript, widgets.Input):\n    input_type = 'hidden'\n    choose_one_text = _(\"Choose an item\")\n    choose_another_text = _(\"Choose another item\")\n    clear_choice_text = _(\"Clear choice\")\n    link_to_chosen_text = _(\"Edit this item\")\n    show_edit_link = True\n\n    def get_instance(self, model_class, value):\n        # helper method for cleanly turning 'value' into an instance object\n        if value is None:\n            return None\n\n        try:\n            return model_class.objects.get(pk=value)\n        except model_class.DoesNotExist:\n            return None\n\n    def get_instance_and_id(self, model_class, value):\n        if value is None:\n            return (None, None)\n        elif isinstance(value, model_class):\n            return (value, value.pk)\n        else:\n            try:\n                return (model_class.objects.get(pk=value), value)\n            except model_class.DoesNotExist:\n                return (None, None)\n\n    def value_from_datadict(self, data, files, name):\n        # treat the empty string as None\n        result = super(AdminChooser, self).value_from_datadict(data, files, name)\n        if result == '':\n            return None\n        else:\n            return result\n\n    def __init__(self, **kwargs):\n        # allow choose_one_text / choose_another_text to be overridden per-instance\n        if 'choose_one_text' in kwargs:\n            self.choose_one_text = kwargs.pop('choose_one_text')\n        if 'choose_another_text' in kwargs:\n            self.choose_another_text = kwargs.pop('choose_another_text')\n        if 'clear_choice_text' in kwargs:\n            self.clear_choice_text = kwargs.pop('clear_choice_text')\n        if 'link_to_chosen_text' in kwargs:\n            self.link_to_chosen_text = kwargs.pop('link_to_chosen_text')\n        if 'show_edit_link' in kwargs:\n            self.show_edit_link = kwargs.pop('show_edit_link')\n        super(AdminChooser, self).__init__(**kwargs)\n\n\nclass AdminPageChooser(AdminChooser):\n    choose_one_text = _('Choose a page')\n    choose_another_text = _('Choose another page')\n    link_to_chosen_text = _('Edit this page')\n\n    def __init__(self, content_type=None, **kwargs):\n        super(AdminPageChooser, self).__init__(**kwargs)\n        self._content_type = content_type\n\n    @cached_property\n    def target_content_types(self):\n        target_content_types = self._content_type or ContentType.objects.get_for_model(Page)\n        # Make sure target_content_types is a list or tuple\n        if not isinstance(target_content_types, (list, tuple)):\n            target_content_types = [target_content_types]\n        return target_content_types\n\n    def render_html(self, name, value, attrs):\n        if len(self.target_content_types) == 1:\n            model_class = self.target_content_types[0].model_class()\n        else:\n            model_class = Page\n\n        instance, value = self.get_instance_and_id(model_class, value)\n\n        original_field_html = super(AdminPageChooser, self).render_html(name, value, attrs)\n\n        return render_to_string(\"wagtailadmin/widgets/page_chooser.html\", {\n            'widget': self,\n            'original_field_html': original_field_html,\n            'attrs': attrs,\n            'value': value,\n            'page': instance,\n        })\n\n    def render_js_init(self, id_, name, value):\n        if isinstance(value, Page):\n            page = value\n        else:\n            # Value is an ID look up object\n            if len(self.target_content_types) == 1:\n                model_class = self.target_content_types[0].model_class()\n            else:\n                model_class = Page\n\n            page = self.get_instance(model_class, value)\n\n        parent = page.get_parent() if page else None\n\n        return \"createPageChooser({id}, {content_type}, {parent});\".format(\n            id=json.dumps(id_),\n            content_type=json.dumps([\n                '{app}.{model}'.format(\n                    app=content_type.app_label,\n                    model=content_type.model)\n                for content_type in self.target_content_types\n            ]),\n            parent=json.dumps(parent.id if parent else None))\n", "path": "wagtail/wagtailadmin/widgets.py"}]}