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

Issue:
Searching a queryset of a specific page class with a child_of/descendant_of filter gives error
Searching on a specific page class with the `child_of`/`descendant_of` filter applied, gives the following error:

```
FieldError at /videos/

Cannot filter search results with field "page_ptr_id". Please add index.FilterField('page_ptr_id') to VideoPage.search_fields.
```

Here's an example query that causes this:

``` python
VideoPage.objects.child_of(parent_page).search("foo")
```

It seems to be a combination of a specific queryset and `child_of`/`descendant_of` filter that causes the issue as the following query (which uses the generic page model) works.

``` python
Page.objects.child_of(parent_page).type(VideoPage).search("foo")
```



Discussion:

Resolving patch:
diff --git a/wagtail/wagtailsearch/backends/base.py b/wagtail/wagtailsearch/backends/base.py
--- a/wagtail/wagtailsearch/backends/base.py
+++ b/wagtail/wagtailsearch/backends/base.py
@@ -71,6 +71,10 @@ def _get_filters_from_where_node(self, where_node):
             lookup = where_node.lookup_name
             value = where_node.rhs
 
+            # Ignore pointer fields that show up in specific page type queries
+            if field_attname.endswith('_ptr_id'):
+                return
+
             # Process the filter
             return self._process_filter(field_attname, lookup, value)
 


Test patch:
diff --git a/wagtail/wagtailsearch/tests/test_backends.py b/wagtail/wagtailsearch/tests/test_backends.py
--- a/wagtail/wagtailsearch/tests/test_backends.py
+++ b/wagtail/wagtailsearch/tests/test_backends.py
@@ -117,6 +117,10 @@ def test_child_model(self):
         results = self.backend.search(None, models.SearchTestChild)
         self.assertEqual(set(results), {self.testc, self.testd})
 
+    def test_child_model_with_id_filter(self):
+        results = self.backend.search("World", models.SearchTestChild.objects.filter(id=self.testd.id))
+        self.assertEqual(set(results), {self.testd})
+
     def test_delete(self):
         # Delete one of the objects
         self.backend.delete(self.testa)
Repository: wagtail/wagtail

Issue:
Frontend cache invalidator HTTP Backend doesn't work on Python 2
Passing `method` as a keyword argument does not work on Python < 3.3. It gives an error:

```
__init__() got an unexpected keyword argument 'method'
```

```
request = Request(
            url=urlunparse([
                self.cache_scheme,
                self.cache_netloc,
                url_parsed.path,
                url_parsed.params,
                url_parsed.query,
                url_parsed.fragment
            ]),
            headers={
                'Host': host,
                'User-Agent': 'Wagtail-frontendcache/' + __version__
            },
            method='PURGE'
        )
```

I can work around this issue in my project by specifying a custom backend. I'll have to subclass `Request` to override its `get_method` method.

Additionally, the test suite does not explicitly test the invalidator backends. That's understandable though. Testing network requests isn't easy.



Discussion:

Resolving patch:
diff --git a/wagtail/contrib/wagtailfrontendcache/backends.py b/wagtail/contrib/wagtailfrontendcache/backends.py
--- a/wagtail/contrib/wagtailfrontendcache/backends.py
+++ b/wagtail/contrib/wagtailfrontendcache/backends.py
@@ -11,6 +11,11 @@
 logger = logging.getLogger('wagtail.frontendcache')
 
 
+class PurgeRequest(Request):
+
+    def get_method(self):
+        return 'PURGE'
+
 class BaseBackend(object):
     def purge(self, url):
         raise NotImplementedError
@@ -30,7 +35,7 @@ def purge(self, url):
         if url_parsed.port:
             host += (':' + str(url_parsed.port))
 
-        request = Request(
+        request = PurgeRequest(
             url=urlunparse([
                 self.cache_scheme,
                 self.cache_netloc,
@@ -42,8 +47,7 @@ def purge(self, url):
             headers={
                 'Host': host,
                 'User-Agent': 'Wagtail-frontendcache/' + __version__
-            },
-            method='PURGE'
+            }
         )
 
         try:


Test patch:
Repository: wagtail/wagtail

Issue:
Remove redundant template debug lines from project template
Ref: https://github.com/torchbox/wagtail/blob/9ff7961a3c8f508ad17735cd815335bad12fd67f/wagtail/project_template/project_name/settings/dev.py#L7-L8
#1688

According to https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.backends.django.DjangoTemplates, the 'debug' option on the DjangoTemplates engine defaults to the global DEBUG setting, so setting this here is apparently redundant. (Also, there's no corresponding option for the Jinja2 backend, so setting this for all engines is not strictly correct.)

So, we just need someone to double-check that with these lines removed, template debug info still displays in development mode but not in production.



Discussion:

Resolving patch:
diff --git a/wagtail/project_template/project_name/settings/dev.py b/wagtail/project_template/project_name/settings/dev.py
--- a/wagtail/project_template/project_name/settings/dev.py
+++ b/wagtail/project_template/project_name/settings/dev.py
@@ -5,9 +5,6 @@
 # SECURITY WARNING: don't run with debug turned on in production!
 DEBUG = True
 
-for template_engine in TEMPLATES:
-    template_engine['OPTIONS']['debug'] = True
-
 # SECURITY WARNING: keep the secret key used in production secret!
 SECRET_KEY = '{{ secret_key }}'
 


Test patch:
Repository: wagtail/wagtail

Issue:
Keyerror when sending password reset email
When sending a password reset email, I'm getting an internal error

I'll just share the raven error - hopefully that doesn't review all of the site secrets (probably does)

https://app.getsentry.com/share/issue/37343334302e313233323439393235/



Discussion:
Hi @kutenai,

The error shown here seems to be a failure while rendering the 500 error template. I suspect what's happening here is:
- an error is happening at the server level (e.g. unable to connect to the SMTP server) while sending the email
- as part of the error handling, Django tries to render the 500.html template to send back to the user
- 500.html is extending your base template, which includes the `{% wagtailuserbar %}` tag
- `{% wagtailuserbar %}` expects to find a `request` variable in the template context, but there isn't one (because this is an error response rather than a standard template response)
- this error is the one that ends up being thrown, masking the root cause (i.e. the SMTP error)

We should fix the `{% wagtailuserbar %}` tag so that it gracefully handles the lack of a `request` variable, and simply does nothing in that case. However, as a general rule I'd recommend that you make your 500 error template a plain standalone HTML file, rather than extending the base template - if the thing triggering the 500 error is a general failure (such as your database being down), then your site may well be 'too dead' to perform the usual tasks involved in rendering the page furniture (e.g. retrieving the list of pages to go in the site navigation).


Resolving patch:
diff --git a/wagtail/wagtailadmin/templatetags/wagtailuserbar.py b/wagtail/wagtailadmin/templatetags/wagtailuserbar.py
--- a/wagtail/wagtailadmin/templatetags/wagtailuserbar.py
+++ b/wagtail/wagtailadmin/templatetags/wagtailuserbar.py
@@ -31,8 +31,10 @@ def get_page_instance(context):
 @register.simple_tag(takes_context=True)
 def wagtailuserbar(context, position='bottom-right'):
     # Find request object
-    request = context['request']
-
+    try:
+        request = context['request']
+    except KeyError:
+        return ''
 
     # Don't render if user doesn't have permission to access the admin area
     if not request.user.has_perm('wagtailadmin.access_admin'):


Test patch:
diff --git a/wagtail/wagtailadmin/tests/test_userbar.py b/wagtail/wagtailadmin/tests/test_userbar.py
--- a/wagtail/wagtailadmin/tests/test_userbar.py
+++ b/wagtail/wagtailadmin/tests/test_userbar.py
@@ -36,6 +36,13 @@ def test_userbar_tag(self):
 
         self.assertIn("<!-- Wagtail user bar embed code -->", content)
 
+    def test_userbar_does_not_break_without_request(self):
+        template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}boom")
+        content = template.render(Context({
+        }))
+
+        self.assertEqual("boom", content)
+
     def test_userbar_tag_self(self):
         """
         Ensure the userbar renders with `self` instead of `PAGE_TEMPLATE_VAR`
Repository: wagtail/wagtail

Issue:
Add default icon for TableBlock
As per https://github.com/torchbox/wagtail/pull/1705#issuecomment-216053655. Best to do this after #2417 is merged, to avoid conflicts.



Discussion:

Resolving patch:
diff --git a/wagtail/contrib/table_block/fields.py b/wagtail/contrib/table_block/fields.py
--- a/wagtail/contrib/table_block/fields.py
+++ b/wagtail/contrib/table_block/fields.py
@@ -29,7 +29,6 @@ def render_js_init(self, id_, name, value):
         return "initTable({0}, {1});".format(json.dumps(id_), json.dumps(self.table_options))
 
 
-
 class TableBlock(FieldBlock):
     def __init__(self, required=True, help_text=None, table_options=None, **kwargs):
         # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality
@@ -102,3 +101,4 @@ def media(self):
     class Meta:
         default = None
         template = 'table_block/blocks/table.html'
+        icon = "table"


Test patch:
Repository: wagtail/wagtail

Issue:
Cannot Edit A Redirect When Set To Just A Forward Slash
I attempted to redirect from the site root to an existing page. E.g. _example.com/_ to _example.com/blog/_. I assumed "Redirect from:" should be set to "/", as all other redirects start with a forward slash. The redirect is successfully added, however, the FROM column field is blank and you cannot click on the redirect to edit it. It also doesn't appear to be functional.

Taking a look at the [following code](https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailredirects/models.py#L55-L68), one can see that it strips any extra white space and removes a trailing slash. If the string is set to only a forward slash, the string is now empty. This doesn't seem to explain why multiple slashes would be set to an empty string, but that's as far as I looked into this issue.

How do we prevent the user from creating a redirect with an empty `old_path`?

If supported, how do we properly redirect from the site root?



Discussion:
Hi @AtomicSpark,

Redirects only take effect on URLs that don't exist as pages (i.e. would return a 404 if the redirect wasn't there), so setting one on the root URL generally won't work. (Actually, it probably will work if you leave your site root page unpublished, but that's not a particularly obvious way of doing it...) We should probably add in a check to disallow an empty 'from' URL, yep.

A better way of achieving what you want to do is to set up a 'redirect' page type, as described here: http://www.coactivate.org/projects/ejucovy/blog/2014/05/10/wagtail-notes-managing-redirects-as-pages/


Resolving patch:
diff --git a/wagtail/wagtailredirects/models.py b/wagtail/wagtailredirects/models.py
--- a/wagtail/wagtailredirects/models.py
+++ b/wagtail/wagtailredirects/models.py
@@ -64,7 +64,7 @@ def normalise_path(url):
         if not path.startswith('/'):
             path = '/' + path
 
-        if path.endswith('/'):
+        if path.endswith('/') and len(path) > 1:
             path = path[:-1]
 
         # Parameters must be sorted alphabetically


Test patch:
diff --git a/wagtail/wagtailredirects/tests.py b/wagtail/wagtailredirects/tests.py
--- a/wagtail/wagtailredirects/tests.py
+++ b/wagtail/wagtailredirects/tests.py
@@ -76,6 +76,8 @@ def test_path_normalisation(self):
             '/Hello/world.htm;fizz=three;buzz=five?foo=Bar&Baz=quux2'
         ))
 
+        self.assertEqual('/', normalise_path('/'))  # '/' should stay '/'
+
         # Normalise some rubbish to make sure it doesn't crash
         normalise_path('This is not a URL')
         normalise_path('//////hello/world')
Repository: wagtail/wagtail

Issue:
Shouldn't use Mutable Default Argument
The chooser's [shared_context method](https://github.com/torchbox/wagtail/blob/197d85ce9f674e319cc7d7d0fa6e0a05dc6a46d7/wagtail/wagtailadmin/views/chooser.py#L13) has a [mutable default argument](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments). 

While the current implementation shouldn't cause any issues (it doesn't actually update the default argument), this should probably be fixed. I'll make a pull request with the changes.



Discussion:

Resolving patch:
diff --git a/wagtail/wagtailadmin/views/chooser.py b/wagtail/wagtailadmin/views/chooser.py
--- a/wagtail/wagtailadmin/views/chooser.py
+++ b/wagtail/wagtailadmin/views/chooser.py
@@ -10,7 +10,7 @@
 from wagtail.wagtailcore.utils import resolve_model_string
 
 
-def shared_context(request, extra_context={}):
+def shared_context(request, extra_context=None):
     context = {
         # parent_page ID is passed as a GET parameter on the external_link and email_link views
         # so that it's remembered when browsing from 'Internal link' to another link type
@@ -20,7 +20,8 @@ def shared_context(request, extra_context={}):
         'allow_external_link': request.GET.get('allow_external_link'),
         'allow_email_link': request.GET.get('allow_email_link'),
     }
-    context.update(extra_context)
+    if extra_context:
+        context.update(extra_context)
     return context
 
 


Test patch:
Repository: wagtail/wagtail

Issue:
draft and live action labels are unclear 
![screen shot 2017-01-05 at 12 42 52](https://cloud.githubusercontent.com/assets/7290588/21680947/944efe00-d344-11e6-9cbd-870f91fe9d5f.png)

I don't think it's clear what the 'draft' and 'live' buttons will do. Could we include the full labels 'Preview draft' and 'View live'? 


Discussion:
NHS UK also found that these buttons were causing confusion in user testing, and have customised them to "View Draft" and "View Live" in their installation:

https://github.com/nhsuk/nhsuk-content-store/blob/383430a9861035f12a679f24a15e15955d87c2a9/nhs_wagtailadmin/locale/en/LC_MESSAGES/django.po#L83-L91

+1 for changing these.
Agreed. I favour 'view' for both. 

Resolving patch:
diff --git a/wagtail/wagtailadmin/wagtail_hooks.py b/wagtail/wagtailadmin/wagtail_hooks.py
--- a/wagtail/wagtailadmin/wagtail_hooks.py
+++ b/wagtail/wagtailadmin/wagtail_hooks.py
@@ -70,10 +70,10 @@ def page_listing_buttons(page, page_perms, is_parent=False):
         yield PageListingButton(_('Edit'), reverse('wagtailadmin_pages:edit', args=[page.id]),
                                 attrs={'title': _('Edit this page')}, priority=10)
     if page.has_unpublished_changes:
-        yield PageListingButton(_('Draft'), reverse('wagtailadmin_pages:view_draft', args=[page.id]),
+        yield PageListingButton(_('View draft'), reverse('wagtailadmin_pages:view_draft', args=[page.id]),
                                 attrs={'title': _('Preview draft'), 'target': '_blank'}, priority=20)
     if page.live and page.url:
-        yield PageListingButton(_('Live'), page.url, attrs={'target': "_blank", 'title': _('View live')}, priority=30)
+        yield PageListingButton(_('View live'), page.url, attrs={'target': "_blank", 'title': _('View live')}, priority=30)
     if page_perms.can_add_subpage():
         if is_parent:
             yield Button(_('Add child page'), reverse('wagtailadmin_pages:add_subpage', args=[page.id]),


Test patch:
Repository: wagtail/wagtail

Issue:
Moving a page corrupts the url_path of children pages when using mssql database
https://github.com/wagtail/wagtail/blob/d1978995c20e948d1d06d6818a67b0ccee52c40b/wagtail/core/models.py#L563

The `SUBSTRING` method here is doing the opposite of what it should.
It should take a substring from the right of `url_path` but it is taking substring from the left.

SUBSTRING docs: https://docs.microsoft.com/en-us/sql/t-sql/functions/substring-transact-sql
`SUBSTRING ( expression ,start ,length )`.

This means that when moving a parent page from `/home/parent-slug-old/` to `/home/parent-slug-new/`, it's children are given `url_path = /home/parent-slug-new//home/parent-slug-old/` instead of `url_path = /home/parent-slug-new/child-slug/`



Discussion:
Thanks for the report @mikemonteith! This was previously noticed by @BertrandBordage https://github.com/wagtail/wagtail/pull/3496#pullrequestreview-29945754 but we weren't able to confirm it as a bug due to us lacking a working mssql testing setup.

Resolving patch:
diff --git a/wagtail/core/models.py b/wagtail/core/models.py
--- a/wagtail/core/models.py
+++ b/wagtail/core/models.py
@@ -12,7 +12,7 @@
 from django.core.exceptions import ValidationError
 from django.core.handlers.base import BaseHandler
 from django.core.handlers.wsgi import WSGIRequest
-from django.db import connection, models, transaction
+from django.db import models, transaction
 from django.db.models import Q, Value
 from django.db.models.functions import Concat, Substr
 from django.http import Http404
@@ -556,20 +556,12 @@ def check(cls, **kwargs):
         return errors
 
     def _update_descendant_url_paths(self, old_url_path, new_url_path):
-        if connection.vendor in ('mssql', 'microsoft'):
-            cursor = connection.cursor()
-            cursor.execute("""
-                UPDATE wagtailcore_page
-                SET url_path= CONCAT(%s, (SUBSTRING(url_path, 0, %s)))
-                WHERE path LIKE %s AND id <> %s
-            """, [new_url_path, len(old_url_path) + 1, self.path + '%', self.id])
-        else:
-            (Page.objects
-                .filter(path__startswith=self.path)
-                .exclude(pk=self.pk)
-                .update(url_path=Concat(
-                    Value(new_url_path),
-                    Substr('url_path', len(old_url_path) + 1))))
+        (Page.objects
+            .filter(path__startswith=self.path)
+            .exclude(pk=self.pk)
+            .update(url_path=Concat(
+                Value(new_url_path),
+                Substr('url_path', len(old_url_path) + 1))))
 
     #: Return this page in its most specific subclassed form.
     @cached_property


Test patch:
Repository: wagtail/wagtail

Issue:
Please set up the Wagtail logo to appear as the favicon in readthedocs.
When I have multiple readthedocs tabs open side-by-side, I can't tell which tab is for which set of documentation.  [Here is an example of  a site that has done this](http://linuxmint-installation-guide.readthedocs.io/en/latest/).


Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -151,7 +151,7 @@
 # The name of an image file (within the static path) to use as favicon of the
 # docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
 # pixels large.
-#html_favicon = None
+html_favicon = 'favicon.ico'
 
 # Add any paths that contain custom static files (such as style sheets) here,
 # relative to this directory. They are copied after the builtin static files,


Test patch:
Repository: wagtail/wagtail

Issue:
AppRegistryNotReady("Apps aren't loaded yet.")
### After updating wagtail from 2.1 to 2.2 I get an AppRegistryNotReady error when migrating.

Removing **from .sitemap_generator import Sitemap**
from **wagtail/contrib/sitemaps/__init__.py**
fixed the problem.

Maybe it has something to do with the User model; I use a custom one.


Discussion:
Hi @robslotboom,
I think this is because you have `wagtail.contrib.sitemaps` in INSTALLED_APPS - this hasn't been required since Wagtail 1.10. However, there was never a release note to explicitly tell people to remove it, so I think it's appropriate for us to fix this so that `wagtail.contrib.sitemaps` in INSTALLED_APPS doesn't break... I'll work on a fix now.

Resolving patch:
diff --git a/wagtail/contrib/sitemaps/sitemap_generator.py b/wagtail/contrib/sitemaps/sitemap_generator.py
--- a/wagtail/contrib/sitemaps/sitemap_generator.py
+++ b/wagtail/contrib/sitemaps/sitemap_generator.py
@@ -2,7 +2,6 @@
 
 from django.contrib.sitemaps import Sitemap as DjangoSitemap
 
-from wagtail.core.models import Site
 from wagtail.core.utils import accepts_kwarg
 from wagtail.utils.deprecation import RemovedInWagtail24Warning
 
@@ -23,6 +22,7 @@ def lastmod(self, obj):
     def get_wagtail_site(self):
         site = getattr(self.request, 'site', None)
         if site is None:
+            from wagtail.core.models import Site
             return Site.objects.select_related(
                 'root_page'
             ).get(is_default_site=True)


Test patch:
Repository: wagtail/wagtail

Issue:
Update modeladmin to preserve compatibility with RelatedFieldListFilter / FieldListFilter in Django 2.2+
### Issue Summary

In 2.2, Django has updated it's `RelatedFieldListFilter` and `FieldListFilter` classes to be coupled to a `ModelAdmin.admin_site` property (See https://github.com/django/django/commit/6d4e5feb79f7eabe8a0c7c4b87f25b1a7f87ca0b).

`wagtail.contrib.modeladmin.view.IndexView` piggybacks on these classes to support filters added via `ModelAdmin.list_filter`. But, unlike their Django counterparts, instances of `wagtail.contrib.modeladmin.options.ModelAdmin` have no `admin_site` attribute, so an `AttributeError` is raised when certain filter types are used.

### Proposed fix

After considering the various options, it is looking like the best short-term solution is to import Django's default `admin_site` (`django.contrib.admin.site`) and make that available as `admin_site` on all instances of `ModelAdmin`.

Longer term, it might be worth defining a custom `django.contrib.admin.sites.AdminSite` class within Wagtail, and setting `admin_site` to an instance of that instead. However, reconciling the differences between how the Wagtail and Django admin areas work may prove to be more work than is worth it.


Discussion:

Resolving patch:
diff --git a/wagtail/contrib/modeladmin/options.py b/wagtail/contrib/modeladmin/options.py
--- a/wagtail/contrib/modeladmin/options.py
+++ b/wagtail/contrib/modeladmin/options.py
@@ -1,4 +1,5 @@
 from django.conf.urls import url
+from django.contrib.admin import site as default_django_admin_site
 from django.contrib.auth.models import Permission
 from django.core import checks
 from django.core.exceptions import ImproperlyConfigured
@@ -120,6 +121,10 @@ def __init__(self, parent=None):
             self.model, self.inspect_view_enabled)
         self.url_helper = self.get_url_helper_class()(self.model)
 
+        # Needed to support RelatedFieldListFilter in Django 2.2+
+        # See: https://github.com/wagtail/wagtail/issues/5105
+        self.admin_site = default_django_admin_site
+
     def get_permission_helper_class(self):
         """
         Returns a permission_helper class to help with permission-based logic


Test patch: