internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: wagtail/wagtail

Issue:
Set context_object_name when defining model?
When defining a Wagtail Page model, it would be nice to be able to set the `context_object_name`, e.g. as a `Meta:` field. This would allow the use of meaningful context object names without needing to define a view.


Discussion:
Thanks for the suggestion @brylie! To clarify, are you proposing something like:

    class EventPage(Page):
        start_date = models.DateField()
        end_date = models.DateField()

        class Meta:
            context_object_name = 'event'

so that you can refer to `{{ event.start_date }}` rather than `{{ page.start_date }}` in the template? If so, that sounds good to me. (I guess we'd set that variable in _addition_ to `page`, as it's quite likely that base templates will want to continue doing `<title>{{ page.title }}</title>`, for example.)
Yeah that is it exactly. Basically, I would like to have a meaningful object name in my code, so it is easier to understand and explain. Keeping `page` around is fine.

Resolving patch:
diff --git a/wagtail/core/models.py b/wagtail/core/models.py
--- a/wagtail/core/models.py
+++ b/wagtail/core/models.py
@@ -750,13 +750,20 @@ def unpublish(self, set_expired=False, commit=True):
 
             self.revisions.update(approved_go_live_at=None)
 
+    context_object_name = None
+
     def get_context(self, request, *args, **kwargs):
-        return {
+        context = {
             PAGE_TEMPLATE_VAR: self,
             'self': self,
             'request': request,
         }
 
+        if self.context_object_name:
+            context[self.context_object_name] = self
+
+        return context
+
     def get_template(self, request, *args, **kwargs):
         if request.is_ajax():
             return self.ajax_template or self.template


Test patch:
diff --git a/wagtail/core/tests/test_page_model.py b/wagtail/core/tests/test_page_model.py
--- a/wagtail/core/tests/test_page_model.py
+++ b/wagtail/core/tests/test_page_model.py
@@ -500,6 +500,17 @@ def test_serve_with_multiple_sites(self):
         response = c.get('/christmas/', HTTP_HOST='localhost')
         self.assertEqual(response.status_code, 404)
 
+    def test_serve_with_custom_context_name(self):
+        EventPage.context_object_name = 'event_page'
+        christmas_page = EventPage.objects.get(url_path='/home/events/christmas/')
+
+        response = self.client.get('/events/christmas/')
+
+        # Context should contain context_object_name key along with standard page keys
+        self.assertEqual(response.context['event_page'], christmas_page)
+        self.assertEqual(response.context['page'], christmas_page)
+        self.assertEqual(response.context['self'], christmas_page)
+
     def test_serve_with_custom_context(self):
         response = self.client.get('/events/')
         self.assertEqual(response.status_code, 200)
Repository: wagtail/wagtail

Issue:
Typo in wagtail/core/middleware.py warning
The second line of the warning in `wagtail/core/middleware.py` should read:

`    'Please update your code to use Site.find_for_request(request) in place of request.site, '`

instead of:

`    'Please update your code to use Site.get_for_request(request) in place of request.site, '`



Discussion:

Resolving patch:
diff --git a/wagtail/core/middleware.py b/wagtail/core/middleware.py
--- a/wagtail/core/middleware.py
+++ b/wagtail/core/middleware.py
@@ -7,7 +7,7 @@
 
 warnings.warn(
     'wagtail.core.middleware.SiteMiddleware and the use of request.site is deprecated. '
-    'Please update your code to use Site.get_for_request(request) in place of request.site, '
+    'Please update your code to use Site.find_for_request(request) in place of request.site, '
     'and remove wagtail.core.middleware.SiteMiddleware from MIDDLEWARES',
     RemovedInWagtail211Warning
 )


Test patch:
Repository: wagtail/wagtail

Issue:
Missing SVG icons for optional rich text features
### Issue Summary

Wagtail doesn't provide SVG icons for optional rich text features like strikethrough, superscript and subscript. It would also be a good addition to provide an SVG icon for underline as well, even though this rich feature is not implemented at the moment.

### Steps to Reproduce

1. Enable the "strikethrough" rich feature:

```python
class RichTextBlock(blocks.RichTextBlock):

    def __init__(self, **kwargs):
        super().__init__(
            features=[
                'bold',
                'italic',
                'strikethrough',
            ],
            **kwargs)
```

2. Check the rich editor menu and see the empty space where it's supposed to be an icon.

![Screenshot 2020-07-28 at 13 30 58](https://user-images.githubusercontent.com/3457859/88666048-70f6f400-d0d7-11ea-8499-36f0f7989803.png)

* I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: (yes / no)

Yes

### Technical details

* Python version: Run `python --version`.
```
Python 3.8.3
```
* Django version: Look in your requirements.txt, or run `pip show django | grep Version`.
```
Version: 3.0.8
```
* Wagtail version: Look at the bottom of the Settings menu in the Wagtail admin, or run `pip show wagtail | grep Version:`.
```
Version: 2.10rc1
```
* Browser version: You can use https://www.whatsmybrowser.org/ to find this out.
```
Chrome 84
```


Discussion:
The icons that need adding are:

Name | FontAwesome link
------|-------------------
superscript | https://fontawesome.com/icons/superscript?style=solid
subscript | https://fontawesome.com/icons/subscript?style=solid
strikethrough | https://fontawesome.com/icons/strikethrough?style=solid

Resolving patch:
diff --git a/wagtail/admin/wagtail_hooks.py b/wagtail/admin/wagtail_hooks.py
--- a/wagtail/admin/wagtail_hooks.py
+++ b/wagtail/admin/wagtail_hooks.py
@@ -780,7 +780,10 @@ def register_icons(icons):
         'site.svg',
         'snippet.svg',
         'spinner.svg',
+        'strikethrough.svg',
         'success.svg',
+        'subscript.svg',
+        'superscript.svg',
         'table.svg',
         'tag.svg',
         'tasks.svg',


Test patch:
Repository: wagtail/wagtail

Issue:
More ugettext deprecation warnings
### Issue Summary

New moderation workflow code has added more instances of ugettext, which was previously fixed in #5907 and bb2e460c0b92fba802fc3f369730004d6b648e64.

Tested this on a project with Wagtail 2.10rc2 - although it's only a deprecation warning.

```
/Users/tomkins/.virtualenvs/tmp-7f32ad0743b7cf9/src/wagtail/wagtail/admin/forms/workflows.py:16: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy().
  q = forms.CharField(label=__("Search term"), widget=forms.TextInput(), required=False)
/Users/tomkins/.virtualenvs/tmp-7f32ad0743b7cf9/src/wagtail/wagtail/admin/views/workflows.py:39: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy().
  page_title = _("Workflows")
/Users/tomkins/.virtualenvs/tmp-7f32ad0743b7cf9/src/wagtail/wagtail/admin/views/workflows.py:40: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy().
  add_item_label = _("Add a workflow")
/Users/tomkins/.virtualenvs/tmp-7f32ad0743b7cf9/src/wagtail/wagtail/admin/views/workflows.py:61: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy().
  page_title = _("New workflow")

(more lines snipped)
```

### Steps to Reproduce

```
pip install -e git+https://github.com/wagtail/wagtail.git@master#egg=wagtail
wagtail start warningdemo
cd warningdemo
python -Wall manage.py migrate
```

And you'll see the deprecation warnings.

### Technical details

* Python version: All
* Django version: 3.0.8
* Wagtail version: 2.10rc2 and master




Discussion:

Resolving patch:
diff --git a/wagtail/admin/forms/workflows.py b/wagtail/admin/forms/workflows.py
--- a/wagtail/admin/forms/workflows.py
+++ b/wagtail/admin/forms/workflows.py
@@ -1,8 +1,8 @@
 from django import forms
 from django.core.exceptions import ImproperlyConfigured, ValidationError
 from django.utils.functional import cached_property
-from django.utils.translation import ugettext as _
-from django.utils.translation import ugettext_lazy as __
+from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as __
 
 from wagtail.admin import widgets
 from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, ObjectList
diff --git a/wagtail/admin/views/workflows.py b/wagtail/admin/views/workflows.py
--- a/wagtail/admin/views/workflows.py
+++ b/wagtail/admin/views/workflows.py
@@ -9,7 +9,7 @@
 from django.urls import reverse
 from django.utils.functional import cached_property
 from django.utils.http import is_safe_url
-from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import gettext_lazy as _
 from django.utils.translation import ngettext
 from django.views.decorators.http import require_POST
 


Test patch:
Repository: wagtail/wagtail

Issue:
Audit log encounter key error  in LANGUAGE_CODE = 'zh-hans'
Found a bug? Please fill out the sections below. 👍

### Issue Summary

When set LANGUAGE_CODE = 'zh-hans' and open /admin/reports/site-history/ in browser, it will give me a key error, I found the reason was that 'Unknown {action}' is translated into '未知{行为}'  in Chinese so that it cannot be format with key ‘action’. 


### Steps to Reproduce

1. LANGUAGE_CODE = 'zh-hans' 
2.  wagtail/admin/log_action_registry.py
3. message = self.get_messages().get(log_entry.action, _('Unknown {action}').format(action=log_entry.action))

Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead?

* I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: (yes / no)


### Technical details

* Python version: Run `python 3.6`.
* Django version: 3.08`.
* Wagtail version: 2.10`.
* Browser version: Chrome.



Discussion:

Resolving patch:
diff --git a/wagtail/admin/log_action_registry.py b/wagtail/admin/log_action_registry.py
--- a/wagtail/admin/log_action_registry.py
+++ b/wagtail/admin/log_action_registry.py
@@ -47,7 +47,7 @@ def get_messages(self):
         return self.messages
 
     def format_message(self, log_entry):
-        message = self.get_messages().get(log_entry.action, _('Unknown {action}').format(action=log_entry.action))
+        message = self.get_messages().get(log_entry.action, _('Unknown %(action)s') % {'action': log_entry.action})
         if callable(message):
             message = message(log_entry.data)
 
diff --git a/wagtail/core/models.py b/wagtail/core/models.py
--- a/wagtail/core/models.py
+++ b/wagtail/core/models.py
@@ -3756,7 +3756,7 @@ def username(self):
                 return self.user.get_username()
             except self._meta.get_field('user').related_model.DoesNotExist:
                 # User has been deleted
-                return _('user {id} (deleted)').format(id=self.user_id)
+                return _('user %(id)d (deleted)') % {'id': self.user_id}
         else:
             return _('system')
 


Test patch:
Repository: wagtail/wagtail

Issue:
Copying unsaved pages works
Just discovered an accidental Wagtail feature. Not sure if it's a bug. You can copy an unsaved page. For example:

```python
mypage = SimplePage(title="Foo page", slug="foo")
mypage.copy(to=homepage)
```

This actually works, it'll create the SimplePage. There aren't any tests for this, except for one test that appears to use it accidentally: https://github.com/wagtail/wagtail/blob/11561822839c0ad7d8a8c454eb3e2800e2fd78bd/wagtail/core/tests/test_page_model.py#L1196-L1202

I'm thinking we should block this, it's easy enough to create pages properly and this will probably lead to confusing logs (after the logging PR is merged).


Discussion:

Resolving patch:
diff --git a/wagtail/core/models.py b/wagtail/core/models.py
--- a/wagtail/core/models.py
+++ b/wagtail/core/models.py
@@ -1756,6 +1756,10 @@ def copy(self, recursive=False, to=None, update_attrs=None, copy_revisions=True,
         :param log_action flag for logging the action. Pass None to skip logging.
             Can be passed an action string. Defaults to 'wagtail.copy'
         """
+
+        if self._state.adding:
+            raise RuntimeError('Page.copy() called on an unsaved page')
+
         exclude_fields = self.default_exclude_fields_in_copy + self.exclude_fields_in_copy + (exclude_fields or [])
         specific_self = self.specific
         if keep_live:


Test patch:
diff --git a/wagtail/core/tests/test_page_model.py b/wagtail/core/tests/test_page_model.py
--- a/wagtail/core/tests/test_page_model.py
+++ b/wagtail/core/tests/test_page_model.py
@@ -1484,6 +1484,12 @@ def test_copy_page_with_excluded_parental_and_child_relations(self):
             # reset excluded fields for future tests
             EventPage.exclude_fields_in_copy = []
 
+    def test_copy_unsaved_page(self):
+        """Test that unsaved page will not be copied."""
+        new_page = SimplePage(slug='testpurp', title='testpurpose')
+        with self.assertRaises(RuntimeError):
+            new_page.copy()
+
 
 class TestCopyForTranslation(TestCase):
     fixtures = ['test.json']
Repository: wagtail/wagtail

Issue:
Change code block style in the docs
The colours in our existing code blocks fail WCAG AA on contrast: https://webaim.org/resources/contrastchecker/?fcolor=408090&bcolor=EEFFCC

See an example here: https://docs.wagtail.io/en/stable/advanced_topics/performance.html#cache

It looks like ``sphinx-rtd-theme`` uses a different style for their own docs: https://sphinx-rtd-theme.readthedocs.io/en/latest/demo/demo.html#code-blocks so maybe we should switch to that.


Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -115,7 +115,7 @@
 #show_authors = False
 
 # The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
+pygments_style = 'default'
 
 # A list of ignored prefixes for module index sorting.
 #modindex_common_prefix = []


Test patch:
Repository: wagtail/wagtail

Issue:
Hallo editor does not work in StructBlock
I upgraded an old Wagtail project to test Wagtail 2.13rc1 and found that text is not rendered into the Hallo.js rich text editor if the editor is part of a StructBlock. The editor behaves just fine if it is used in its own RichTextField. 

### Steps to Reproduce

I created a minimal repository to demostrate this issue: https://github.com/cnk/hallo-issue I have included the sqlite database in the repository so you should be able to see this in action by: 

1. check out https://github.com/cnk/hallo-issue
2. Activate a virtual environment and `pip install -r requirements.txt`
3. `./manage.py createsuperuser`
4. `./manage.py runserver`

### Technical details

* Python version: I used 3.7.7
* Django version: 3.2
* Wagtail version: 2.13rc1
* Browser version: I tried it with Firefox and Chrome.



Discussion:

Resolving patch:
diff --git a/wagtail/admin/rich_text/editors/hallo.py b/wagtail/admin/rich_text/editors/hallo.py
--- a/wagtail/admin/rich_text/editors/hallo.py
+++ b/wagtail/admin/rich_text/editors/hallo.py
@@ -9,6 +9,8 @@
 from wagtail.admin.rich_text.converters.editor_html import EditorHTMLConverter
 from wagtail.admin.staticfiles import versioned_static
 from wagtail.core.rich_text import features
+from wagtail.core.telepath import register
+from wagtail.core.widget_adapters import WidgetAdapter
 
 
 class HalloPlugin:
@@ -162,3 +164,10 @@ def media(self):
             media += plugin.media
 
         return media
+
+
+class HalloRichTextAreaAdapter(WidgetAdapter):
+    js_constructor = 'wagtail.widgets.HalloRichTextArea'
+
+
+register(HalloRichTextAreaAdapter(), HalloRichTextArea)


Test patch:
Repository: wagtail/wagtail

Issue:
BaseLogEntry.comment property removed but still referenced in docs
As noted on https://github.com/wagtail/wagtail/commit/122f509b1d6d7ec5afa3da5ba1bc4165c2e2d105#r50371417, moving the comment formatting logic from BaseLogEntry to LogActionRegistry has broken a documented API:

> The `comment` property here is part of the documented API for BaseLogEntry at https://github.com/wagtail/wagtail/blob/main/docs/reference/pages/model_reference.rst#baselogentry, so this probably needs to be preserved (or formally deprecated) - as it stands, this is throwing a warning when building the docs.


Discussion:
Good catch, thanks! I agree we should replace/formally deprecate this, but I believe this code should only be in `main` and not `stable/2.13.x` as we're targetting 2.14 for any audit logging changes - so I think this shouldn't block the 2.13 release, unless I'm missing something.
Ah yep - was panicking too much there :-) Thanks!

Resolving patch:
diff --git a/wagtail/core/models.py b/wagtail/core/models.py
--- a/wagtail/core/models.py
+++ b/wagtail/core/models.py
@@ -4871,6 +4871,10 @@ def format_message(self):
     def format_comment(self):
         return self.action_registry.format_comment(self)
 
+    @property
+    def comment(self):
+        return self.format_comment()
+
 
 class PageLogEntry(BaseLogEntry):
     page = models.ForeignKey(


Test patch:
diff --git a/wagtail/core/tests/test_audit_log.py b/wagtail/core/tests/test_audit_log.py
--- a/wagtail/core/tests/test_audit_log.py
+++ b/wagtail/core/tests/test_audit_log.py
@@ -263,7 +263,7 @@ def test_workflow_actions(self):
         for action in ['approve', 'reject']:
             with self.subTest(action):
                 task_state = workflow_state.current_task_state
-                task_state.task.on_action(task_state, user=None, action_name=action)
+                task_state.task.on_action(task_state, user=None, action_name=action, comment="This is my comment")
                 workflow_state.refresh_from_db()
 
                 entry = PageLogEntry.objects.filter(action='wagtail.workflow.{}'.format(action))
@@ -283,8 +283,9 @@ def test_workflow_actions(self):
                             'title': workflow_state.current_task_state.task.name,
                         },
                     },
-                    'comment': '',
+                    'comment': 'This is my comment',
                 })
+                self.assertEqual(entry[0].comment, "This is my comment")
 
     def test_workflow_completions_logs_publishing_user(self):
         workflow = Workflow.objects.create(name='test_workflow')
Repository: wagtail/wagtail

Issue:
Site history report n+1s
While checking Scout APM for a client project with lots of different authors and overall activity, I've noticed that the site history report has a few N+1s.

![wagtail-log-views-report-n-plus-one](https://user-images.githubusercontent.com/31622/123254960-349a6680-d4e7-11eb-87ec-a0f0ea452c5e.png)



Discussion:
@zerolab I think site history (as opposed to page history) still needs fixing separately. I did have a fix as part of https://github.com/gasman/wagtail/commits/feature/model-audit-log , but ended up having to roll it back due to other non-deterministic weirdness going on in that branch...
Indeed. My reopening of the issue (and deleting the incorrect comment) is a reflection of that. Got overly excited 🤣
How far along is the model audit log? Don't want to submit a PR for this if the other work will come through in time for 2.14
Model audit log is only at the proof-of-concept stage right now and not expected to be done for 2.14, so feel free to go ahead with a PR.

Resolving patch:
diff --git a/wagtail/admin/views/reports/audit_logging.py b/wagtail/admin/views/reports/audit_logging.py
--- a/wagtail/admin/views/reports/audit_logging.py
+++ b/wagtail/admin/views/reports/audit_logging.py
@@ -74,9 +74,7 @@ def get_filename(self):
         )
 
     def get_queryset(self):
-        q = Q(
-            page__in=UserPagePermissionsProxy(self.request.user).explorable_pages().values_list('pk', flat=True)
-        )
+        q = Q(page__in=UserPagePermissionsProxy(self.request.user).explorable_pages())
 
         root_page_permissions = Page.get_first_root_node().permissions_for_user(self.request.user)
         if (
@@ -88,7 +86,11 @@ def get_queryset(self):
                 PageLogEntry.objects.filter(deleted=True).values('page_id')
             ))
 
-        return PageLogEntry.objects.filter(q)
+        # Using prefech_related() on page, as select_related() generates an INNER JOIN,
+        # which filters out entries for deleted pages
+        return PageLogEntry.objects.filter(q).select_related(
+            'user', 'user__wagtail_userprofile'
+        ).prefetch_related('page')
 
     def get_action_label(self, action):
         from wagtail.core.log_actions import page_log_action_registry


Test patch:
Repository: wagtail/wagtail

Issue:
Allow long URLs migration fails upgrading wagtail to 2.13.3
### Issue Summary

Hello, I'm upgrading an existing Wagtail site 2.7.3 to 2.13.3. All worked fine on my test database, but when running the migrations on production data I encountered the following error when `wagtailembeds.0008_allow_long_urls` was applied:

```
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(200)
```

After a bit of digging, I found that my production data has a couple of Embed objects with `thumbnail_url` lengths greater than 200.

This seemed OK, as Wagtail 2.7.3 has `thumbnail_url` max length of 255:

```
thumbnail_url = models.URLField(max_length=255, null=True, blank=True)
```

I tried a quick fix by updating the `wagtailembeds.0008_allow_long_urls` migration by adding `max_length=255`. It seemed to fix the problem and the migration ran OK on my production data.

However, I'm not sure if this is the preferred or right solution:

```
migrations.AlterField(
    model_name="embed",
    name="thumbnail_url",
    field=models.URLField(
        blank=True,
        default="",
        max_length=255,
    ),
    preserve_default=False,
),
```

### Steps to Reproduce

I have only tried this on a existing Wagtail instance, but I suppose it could be recreated on a fresh (but older 2.7.3?) instance of Wagtail, creating an Embed object with a `thumbnail_url` greater that 200 in length and then migrating to the latest Wagtail (2.13.3).

* I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: No


### Technical details

* Python version: Python 3.6.4
* Django version: 3.2.5
* Wagtail version: 2.13.3
* Browser version: N/A



Discussion:
Thanks for the report @marts! I think your suggested fix is correct - the AlterField operation in question is only needed [as a workaround for a MySQL issue](https://github.com/wagtail/wagtail/pull/6999), and is immediately followed by changing it to a TextField where max_length doesn't apply. Other than the addition of `default=""`, the field definition here _should_ have matched the previous state, namely [the one set in migration 0005](https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/migrations/0005_specify_thumbnail_url_max_length.py) - but the max_length was missed here.

Marking this as for 2.13.4 - while 2.14 is coming pretty soon, we ought to put out a 2.12.x and 2.13.x release with this fix as it's a potential blocker for people doing point-by-point upgrades.

Resolving patch:
diff --git a/wagtail/embeds/migrations/0008_allow_long_urls.py b/wagtail/embeds/migrations/0008_allow_long_urls.py
--- a/wagtail/embeds/migrations/0008_allow_long_urls.py
+++ b/wagtail/embeds/migrations/0008_allow_long_urls.py
@@ -34,6 +34,7 @@ class Migration(migrations.Migration):
             field=models.URLField(
                 blank=True,
                 default="",
+                max_length=255,
             ),
             preserve_default=False,
         ),


Test patch: