Dataset Viewer
Auto-converted to Parquet
repo_name
stringclasses
5 values
task_num
int64
1.48k
57.7k
gold_patch
stringlengths
717
987k
commit
stringlengths
40
40
edit_prompt
stringlengths
37
322
prompt
stringlengths
442
21.9k
edit_patch
stringlengths
415
6.38k
test_patch
stringlengths
573
27.4k
autocomplete_prompts
stringlengths
210
1.61k
autocomplete_patch
stringlengths
415
5.55k
wagtail
12,562
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index af11687f0936..d42ae5cc9e7a 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -15,6 +15,7 @@ Changelog * Fix: Fix animation overflow transition when navigating through subpages in the sidebar page explorer (manu) * Fix: Ensure form builder supports custom admin form validation (John-Scott Atlakson, LB (Ben) Johnston) * Fix: Ensure form builder correctly checks for duplicate field names when using a custom related name (John-Scott Atlakson, LB (Ben) Johnston) + * Fix: Normalize `StreamField.get_default()` to prevent creation forms from breaking (Matt Westcott) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) * Docs: Move the tags documentation to standalone advanced topic, instead of being inside the reference/pages section (Srishti Jaiswal) diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 159ed656e185..cc049a481439 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -28,6 +28,7 @@ depth: 1 * Fix animation overflow transition when navigating through subpages in the sidebar page explorer (manu) * Ensure form builder supports custom admin form validation (John-Scott Atlakson, LB (Ben) Johnston) * Ensure form builder correctly checks for duplicate field names when using a custom related name (John-Scott Atlakson, LB (Ben) Johnston) + * Normalize `StreamField.get_default()` to prevent creation forms from breaking (Matt Westcott) ### Documentation diff --git a/wagtail/fields.py b/wagtail/fields.py index 79eae7a66eb8..cfacc3c2582b 100644 --- a/wagtail/fields.py +++ b/wagtail/fields.py @@ -239,6 +239,9 @@ def formfield(self, **kwargs): defaults.update(kwargs) return super().formfield(**defaults) + def get_default(self): + return self.stream_block.normalize(super().get_default()) + def value_to_string(self, obj): # This method is used for serialization using django.core.serializers, # which is used by dumpdata and loaddata for serializing model objects.
210f35f7ec42d8ead1508cde52f421631f8621b8
Normalize StreamField.get_default using the stream_block.
The following is the text of a github issue and related comments for this repository: Complex StreamField default values fail on snippet creation form ### Issue Summary Passing a list of (block_type, value) tuples as the default value of a StreamField on a snippet model causes the snippet creation view to fail with `'tuple' object has no attribute 'block'`. The same StreamField definition works as expected on a page model. This apparently happens because the page creation view creates an initial instance of the page to pass to the form, but `wagtail.admin.views.generic.models.CreateView` (as used for snippets) [constructs the form instance with no initial instance](https://github.com/wagtail/wagtail/blob/246f3c7eb542be2081556bf5334bc22256776bf4/wagtail/admin/views/generic/models.py#L575-L579) (unless the model is localized). ### Steps to Reproduce Start a new project with `wagtail start myproject` and edit home/models.py as follows: ```python from django.db import models from wagtail.models import Page from wagtail.snippets.models import register_snippet from wagtail.fields import StreamField from wagtail import blocks from wagtail.admin.panels import FieldPanel class HomePage(Page): sprint_days = StreamField( [ ('day', blocks.StructBlock([ ('title', blocks.CharBlock()), ('text', blocks.TextBlock()), ])) ], blank=True, use_json_field=True, default=[ ("day", {"title": "First", "text": "Test"}), ("day", {"title": "Second", "text": "Test"}), ], ) content_panels = Page.content_panels + [ FieldPanel("sprint_days"), ] @register_snippet class ProcessInfo(models.Model): sprint_days = StreamField( [ ('day', blocks.StructBlock([ ('title', blocks.CharBlock()), ('text', blocks.TextBlock()), ])) ], blank=True, use_json_field=True, default=[ ("day", {"title": "First", "text": "Test"}), ("day", {"title": "Second", "text": "Test"}), ], ) panels = [ FieldPanel("sprint_days"), ] ``` Log in to the admin, go to Snippets -> Process infos and attempt to create a ProcessInfo snippet. The create view fails to render, with the following exception being thrown: <details> ``` Environment: Request Method: GET Request URL: http://localhost:8000/admin/snippets/home/processinfo/add/ Django Version: 5.1.3 Python Version: 3.10.4 Installed Applications: ['home', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Template error: In template /Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/templates/wagtailadmin/panels/object_list.html, error at line 9 'tuple' object has no attribute 'block' 1 : {% load wagtailadmin_tags %} 2 : 3 : <div class="w-form-width" {% include "wagtailadmin/shared/attrs.html" with attrs=self.attrs %}> 4 : {% if self.help_text %} 5 : {% help_block status="info" %}{{ self.help_text }}{% endhelp_block %} 6 : {% endif %} 7 : {% for child, identifier in self.visible_children_with_identifiers %} 8 : {% panel id_prefix=self.prefix id=identifier classname=child.classes|join:' ' attrs=child.attrs heading=child.heading heading_size="label" icon=child.icon id_for_label=child.id_for_label is_required=child.is_required %} 9 : {% component child %} 10 : {% endpanel %} 11 : {% endfor %} 12 : </div> 13 : Traceback (most recent call last): File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/auth.py", line 171, in overridden_render return render() File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/backends/django.py", line 107, in render return self.template.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 65, in render result = block.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 65, in render result = block.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 65, in render result = block.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/loader_tags.py", line 65, in render result = block.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/defaulttags.py", line 327, in render return nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1067, in render output = self.filter_expression.resolve(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 718, in resolve obj = self.var.resolve(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 850, in resolve value = self._resolve_lookup(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 917, in _resolve_lookup current = current() File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/panels/base.py", line 317, in render_form_content return mark_safe(self.render_html() + self.render_missing_fields()) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/laces/components.py", line 55, in render_html return template.render(context_data) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/backends/django.py", line 107, in render return self.template.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/defaulttags.py", line 243, in render nodelist.append(node.render_annotated(context)) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py", line 1099, in render children = self.nodelist.render(context) if self.nodelist else "" File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 1008, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/template/base.py", line 969, in render_annotated return self.render(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/laces/templatetags/laces.py", line 81, in render html = component.render_html(context) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/laces/components.py", line 50, in render_html context_data = self.get_context_data(parent_context) File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/panels/field_panel.py", line 273, in get_context_data context.update(self.get_editable_context_data()) File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/admin/panels/field_panel.py", line 315, in get_editable_context_data rendered_field = self.bound_field.as_widget(attrs=widget_attrs) File "/Users/matthew/.virtualenvs/wagtailstreamdefault/lib/python3.10/site-packages/django/forms/boundfield.py", line 108, in as_widget return widget.render( File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/blocks/base.py", line 619, in render return self.render_with_errors( File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/blocks/base.py", line 599, in render_with_errors value_json = json.dumps(self.block_def.get_form_state(value)) File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/blocks/stream_block.py", line 354, in get_form_state return [ File "/Users/matthew/Development/tbx/wagtail/devscript/wagtail/wagtail/blocks/stream_block.py", line 356, in <listcomp> "type": child.block.name, Exception Type: AttributeError at /admin/snippets/home/processinfo/add/ Exception Value: 'tuple' object has no attribute 'block' ``` </details> However, creating a new HomePage results in the form being populated with the two default block values as expected. - I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes ### Technical details - Python version: 3.10.4 - Django version: 5.1.3 - Wagtail version: 6.4a0 ### Working on this I'm working on a PR now. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/fields.py b/wagtail/fields.py index 79eae7a66eb8..cfacc3c2582b 100644 --- a/wagtail/fields.py +++ b/wagtail/fields.py @@ -239,6 +239,9 @@ def formfield(self, **kwargs): defaults.update(kwargs) return super().formfield(**defaults) + def get_default(self): + return self.stream_block.normalize(super().get_default()) + def value_to_string(self, obj): # This method is used for serialization using django.core.serializers, # which is used by dumpdata and loaddata for serializing model objects.
diff --git a/wagtail/tests/test_streamfield.py b/wagtail/tests/test_streamfield.py index 461986ba565c..36173ac299a9 100644 --- a/wagtail/tests/test_streamfield.py +++ b/wagtail/tests/test_streamfield.py @@ -297,6 +297,18 @@ def test_default_value(self): self.assertEqual(self.page.body[1].value[1].block_type, "author") self.assertEqual(self.page.body[1].value[1].value, "F. Scott Fitzgerald") + def test_creation_form_with_initial_instance(self): + form_class = ComplexDefaultStreamPage.get_edit_handler().get_form_class() + form = form_class(instance=self.page) + form_html = form.as_p() + self.assertIn("The Great Gatsby", form_html) + + def test_creation_form_without_initial_instance(self): + form_class = ComplexDefaultStreamPage.get_edit_handler().get_form_class() + form = form_class() + form_html = form.as_p() + self.assertIn("The Great Gatsby", form_html) + class TestStreamFieldRenderingBase(TestCase): model = JSONStreamModel
diff --git a/wagtail/fields.py b/wagtail/fields.py index 79eae7a66eb8..cfacc3c2582b 100644 --- a/wagtail/fields.py +++ b/wagtail/fields.py @@ -239,6 +239,9 @@ def formfield(self, **kwargs): def get_default(
diff --git a/wagtail/fields.py b/wagtail/fields.py index 79eae7a66eb8..cfacc3c2582b 100644 --- a/wagtail/fields.py +++ b/wagtail/fields.py @@ -239,6 +239,9 @@ def formfield(self, **kwargs): defaults.update(kwargs) return super().formfield(**defaults) + def get_default(self): + return self.stream_block.normalize(super().get_default()) + def value_to_string(self, obj): # This method is used for serialization using django.core.serializers, # which is used by dumpdata and loaddata for serializing model objects.
wagtail
12,750
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 4631b5a8daa..fa0abb8ce5e 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -41,6 +41,7 @@ Changelog * Fix: Return never-cache HTTP headers when serving pages and documents with view restrictions (Krystian Magdziarz, Dawid Bugajewski) * Fix: Implement `get_block_by_content_path` on `ImageBlock` to prevent errors on commenting (Matt Westcott) * Fix: Add `aria-expanded` attribute to new column button on `TypedTableBlock` to reflect menu state (Ayaan Qadri, Scott Cranfill) + * Fix: Allow page models to extend base `Page` panel definitions without importing `wagtail.admin` (Matt Westcott) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) * Docs: Move the tags documentation to standalone advanced topic, instead of being inside the reference/pages section (Srishti Jaiswal) diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 5532e9d6a27..7beaf864690 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -53,6 +53,7 @@ depth: 1 * Return never-cache HTTP headers when serving pages and documents with view restrictions (Krystian Magdziarz, Dawid Bugajewski) * Implement `get_block_by_content_path` on `ImageBlock` to prevent errors on commenting (Matt Westcott) * Add `aria-expanded` attribute to new column button on `TypedTableBlock` to reflect menu state (Ayaan Qadri, Scott Cranfill) + * Allow page models to extend base `Page` panel definitions without importing `wagtail.admin` (Matt Westcott) ### Documentation @@ -170,6 +171,11 @@ The old style will now produce a deprecation warning. ## Upgrade considerations - changes to undocumented internals +### Changes to `content_panels`, `promote_panels` and `settings_panels` values on base `Page` model + +Previously, the `content_panels`, `promote_panels` and `settings_panels` attributes on the base `Page` model were defined as lists of `Panel` instances. These lists now contain instances of `wagtail.models.PanelPlaceholder` instead, which are resolved to `Panel` instances at runtime. Panel definitions that simply extend these lists (such as `content_panels = Page.content_panels + [...]`) are unaffected; however, any logic that inspects these lists (for example, finding a panel in the list to insert a new one immediately after it) will need to be updated to handle the new object types. + + ### Removal of unused Rangy JS library The unused JavaScript include `wagtailadmin/js/vendor/rangy-core.js` has been removed from the editor interface, and functions such as `window.rangy.getSelection()` are no longer available. Any code relying on this should now either supply its own copy of the [Rangy library](https://github.com/timdown/rangy), or be migrated to the official [`Document.createRange()`](https://developer.mozilla.org/en-US/docs/Web/API/Range) browser API. diff --git a/wagtail/admin/panels/model_utils.py b/wagtail/admin/panels/model_utils.py index 0b98a81992f..dd18f615b12 100644 --- a/wagtail/admin/panels/model_utils.py +++ b/wagtail/admin/panels/model_utils.py @@ -5,6 +5,7 @@ from django.forms.models import fields_for_model from wagtail.admin.forms.models import formfield_for_dbfield +from wagtail.models import PanelPlaceholder from .base import Panel from .field_panel import FieldPanel @@ -62,6 +63,10 @@ def expand_panel_list(model, panels): if isinstance(panel, Panel): result.append(panel) + elif isinstance(panel, PanelPlaceholder): + if real_panel := panel.construct(): + result.append(real_panel) + elif isinstance(panel, str): field = model._meta.get_field(panel) if isinstance(field, ManyToOneRel): diff --git a/wagtail/admin/panels/page_utils.py b/wagtail/admin/panels/page_utils.py index 58116638b1c..093ee5330f2 100644 --- a/wagtail/admin/panels/page_utils.py +++ b/wagtail/admin/panels/page_utils.py @@ -1,50 +1,12 @@ -from django.conf import settings from django.utils.translation import gettext_lazy from wagtail.admin.forms.pages import WagtailAdminPageForm from wagtail.models import Page from wagtail.utils.decorators import cached_classmethod -from .comment_panel import CommentPanel -from .field_panel import FieldPanel -from .group import MultiFieldPanel, ObjectList, TabbedInterface -from .publishing_panel import PublishingPanel -from .title_field_panel import TitleFieldPanel +from .group import ObjectList, TabbedInterface - -def set_default_page_edit_handlers(cls): - cls.content_panels = [ - TitleFieldPanel("title"), - ] - - cls.promote_panels = [ - MultiFieldPanel( - [ - FieldPanel("slug"), - FieldPanel("seo_title"), - FieldPanel("search_description"), - ], - gettext_lazy("For search engines"), - ), - MultiFieldPanel( - [ - FieldPanel("show_in_menus"), - ], - gettext_lazy("For site menus"), - ), - ] - - cls.settings_panels = [ - PublishingPanel(), - ] - - if getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True): - cls.settings_panels.append(CommentPanel()) - - cls.base_form_class = WagtailAdminPageForm - - -set_default_page_edit_handlers(Page) +Page.base_form_class = WagtailAdminPageForm @cached_classmethod diff --git a/wagtail/admin/panels/signal_handlers.py b/wagtail/admin/panels/signal_handlers.py index 0c108f469c7..5c368c12a9b 100644 --- a/wagtail/admin/panels/signal_handlers.py +++ b/wagtail/admin/panels/signal_handlers.py @@ -5,7 +5,6 @@ from wagtail.models import Page from .model_utils import get_edit_handler -from .page_utils import set_default_page_edit_handlers @receiver(setting_changed) @@ -14,7 +13,6 @@ def reset_edit_handler_cache(**kwargs): Clear page edit handler cache when global WAGTAILADMIN_COMMENTS_ENABLED settings are changed """ if kwargs["setting"] == "WAGTAILADMIN_COMMENTS_ENABLED": - set_default_page_edit_handlers(Page) for model in apps.get_models(): if issubclass(model, Page): model.get_edit_handler.cache_clear() diff --git a/wagtail/models/__init__.py b/wagtail/models/__init__.py index 5d2d741e3d9..58c9223339d 100644 --- a/wagtail/models/__init__.py +++ b/wagtail/models/__init__.py @@ -128,6 +128,7 @@ UploadedFile, get_root_collection_id, ) +from .panels import CommentPanelPlaceholder, PanelPlaceholder from .reference_index import ReferenceIndex # noqa: F401 from .sites import Site, SiteManager, SiteRootPath # noqa: F401 from .specific import SpecificMixin @@ -1405,11 +1406,40 @@ class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase): COMMENTS_RELATION_NAME, ] - # Define these attributes early to avoid masking errors. (Issue #3078) - # The canonical definition is in wagtailadmin.panels. - content_panels = [] - promote_panels = [] - settings_panels = [] + # Real panel classes are defined in wagtail.admin.panels, which we can't import here + # because it would create a circular import. Instead, define them with placeholders + # to be replaced with the real classes by `wagtail.admin.panels.model_utils.expand_panel_list`. + content_panels = [ + PanelPlaceholder("wagtail.admin.panels.TitleFieldPanel", ["title"], {}), + ] + promote_panels = [ + PanelPlaceholder( + "wagtail.admin.panels.MultiFieldPanel", + [ + [ + "slug", + "seo_title", + "search_description", + ], + _("For search engines"), + ], + {}, + ), + PanelPlaceholder( + "wagtail.admin.panels.MultiFieldPanel", + [ + [ + "show_in_menus", + ], + _("For site menus"), + ], + {}, + ), + ] + settings_panels = [ + PanelPlaceholder("wagtail.admin.panels.PublishingPanel", [], {}), + CommentPanelPlaceholder(), + ] # Privacy options for page private_page_options = ["password", "groups", "login"] diff --git a/wagtail/models/panels.py b/wagtail/models/panels.py new file mode 100644 index 00000000000..8e3c6066328 --- /dev/null +++ b/wagtail/models/panels.py @@ -0,0 +1,37 @@ +# Placeholder for panel types defined in wagtail.admin.panels. +# These are needed because we wish to define properties such as `content_panels` on core models +# such as Page, but importing from wagtail.admin would create a circular import. We therefore use a +# placeholder object, and swap it out for the real panel class inside +# `wagtail.admin.panels.model_utils.expand_panel_list` at the same time as converting strings to +# FieldPanel instances. + +from django.conf import settings +from django.utils.functional import cached_property +from django.utils.module_loading import import_string + + +class PanelPlaceholder: + def __init__(self, path, args, kwargs): + self.path = path + self.args = args + self.kwargs = kwargs + + @cached_property + def panel_class(self): + return import_string(self.path) + + def construct(self): + return self.panel_class(*self.args, **self.kwargs) + + +class CommentPanelPlaceholder(PanelPlaceholder): + def __init__(self): + super().__init__( + "wagtail.admin.panels.CommentPanel", + [], + {}, + ) + + def construct(self): + if getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True): + return super().construct()
a2407c002770ab7f50997d37571de3cf43f0d455
Create PanelPlaceholder classes that can temporarily stand in for panel types from wagtail.admin.panels, with CommentPanelPlaceholder being a special case that only constructs if comments are enabled.
The following is the text of a github issue and related comments for this repository: Omitting import of `wagtail.admin.panels` causes page title field to be absent ### Issue Summary As of #12557 it is possible to define a page model's `content_panels` as a list of strings, without referring to any panel classes such as `FieldPanel`. However, if `wagtail.admin.panels` is not imported at all, the title field is missing from the edit form. This is because [the call to `set_default_page_edit_handlers` in `wagtail.admin.panels.page_utils`](https://github.com/wagtail/wagtail/blob/7cfae8c3b5b826bc5ba09f9d772e19077b21770b/wagtail/admin/panels/page_utils.py#L47) never gets executed. ### Steps to Reproduce 1. Start a new project with `wagtail start notitle` 2. Edit home/models.py to: ```python from django.db import models from wagtail.models import Page class HomePage(Page): intro = models.TextField(blank=True) content_panels = Page.content_panels + ["intro"] ``` 3. Run ./manage.py makemigrations, ./manage.py migrate, ./manage.py createsuperuser, ./manage.py runserver 4. Log in to admin and visit http://localhost:8000/admin/pages/3/edit/ . The title field is missing: <img width="1141" alt="Image" src="https://github.com/user-attachments/assets/b7d69dad-634b-44c8-8181-416dae46edfe" /> - I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes ### Technical details - Python version: 3.13.0 - Django version: 5.1.4 - Wagtail version: main (6.4a0) ### More Information More specifically: we need to ensure that the properties of Page that are being set in wagtail.admin.panels.page_utils.set_default_page_edit_handlers (primarily content_panels, but also promote_panels, settings_panels and base_form_class) are in place before we reach any code that accesses them. This will often be at the module level of a project models.py file, in code such as content_panels = Page.content_panels + [...]. The call to set_default_page_edit_handlers typically happens through one of two routes: - an import of wagtail.admin.panels in that project-side models.py file (which in turn imports wagtail.admin.panels.page_utils) - the import of wagtail.admin.panels within wagtail.admin.models, which will be reached during startup when Django iterates through INSTALLED_APPS - The latter would be fine if we could guarantee that wagtail.admin appears above any project-side apps in INSTALLED_APPS, but we can't. Now that we've effectively eliminated the reason to import wagtail.admin.panels within user code, it's entirely plausible that wagtail.admin will go entirely unloaded until after a project's page models are set up. This suggests that we can't mitigate this problem just by changing the behaviour of wagtail.admin - we can only rely on the definition of wagtail.models.Page as it comes from the core wagtail app. The final values of Page.content_panels and the other attributes must therefore be defined within wagtail.models, at least in stub form - I don't think there's any way around that. In fact, I think "in stub form" might be the key to solving this. It's unlikely that we can import wagtail.admin.panels into wagtail.models as it currently stands without massive circular dependencies (and even if we could, a two-way dependency between core and admin is definitely not the way we want to go for code maintainability). It's also unclear how much of wagtail.admin.panels we could migrate into wagtail without bringing the rest of wagtail.admin (widgets, templates, classnames that are only meaningful in conjunction with admin CSS...) along for the ride. However, #12557 itself might provide the solution - just as we can define strings as placeholders for FieldPanel and InlinePanel which then get swapped out for the real panel objects in wagtail.admin.panels.model_utils.expand_panel_list, we can define other symbolic placeholders for any other panel types we need for Page, and have expand_panel_list swap those out too. The one drawback I can think of is that it's likely to break existing user code that makes assumptions about the contents of the content_panels / promote_panels lists - for example, "I want to insert social_share_image directly after seo_title in promote_panels, so I'll loop through the contents of promote_panels looking for isinstance(panel, FieldPanel) and panel.name = "seo_title"". I think that's an acceptable breakage to cover in release notes, though. Rather than leaving Page's content_panels, promote_panels and settings_panels initially empty to be populated by set_default_page_edit_handlers in wagtail.admin, define them within wagtail.models as placeholders that get expanded by expand_panel_list at the same time as expanding strings to FieldPanels. This ensures that code such as content_panels = Page.content_panels + [...] does not end up extending the empty list if wagtail.admin has not yet been loaded. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/models/panels.py b/wagtail/models/panels.py new file mode 100644 index 00000000000..8e3c6066328 --- /dev/null +++ b/wagtail/models/panels.py @@ -0,0 +1,37 @@ +# Placeholder for panel types defined in wagtail.admin.panels. +# These are needed because we wish to define properties such as `content_panels` on core models +# such as Page, but importing from wagtail.admin would create a circular import. We therefore use a +# placeholder object, and swap it out for the real panel class inside +# `wagtail.admin.panels.model_utils.expand_panel_list` at the same time as converting strings to +# FieldPanel instances. + +from django.conf import settings +from django.utils.functional import cached_property +from django.utils.module_loading import import_string + + +class PanelPlaceholder: + def __init__(self, path, args, kwargs): + self.path = path + self.args = args + self.kwargs = kwargs + + @cached_property + def panel_class(self): + return import_string(self.path) + + def construct(self): + return self.panel_class(*self.args, **self.kwargs) + + +class CommentPanelPlaceholder(PanelPlaceholder): + def __init__(self): + super().__init__( + "wagtail.admin.panels.CommentPanel", + [], + {}, + ) + + def construct(self): + if getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True): + return super().construct()
diff --git a/wagtail/admin/tests/pages/test_create_page.py b/wagtail/admin/tests/pages/test_create_page.py index 733ac26c263..6bf874e868c 100644 --- a/wagtail/admin/tests/pages/test_create_page.py +++ b/wagtail/admin/tests/pages/test_create_page.py @@ -427,6 +427,26 @@ def test_cannot_create_page_with_wrong_subpage_types(self): ) self.assertRedirects(response, "/admin/") + def test_create_page_defined_before_admin_load(self): + """ + Test that a page model defined before wagtail.admin is loaded has all fields present + """ + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("earlypage", "earlypage", self.root_page.id), + ) + ) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed(response, "wagtailadmin/pages/create.html") + # Title field should be present and have TitleFieldPanel behaviour + # including syncing with slug + self.assertContains(response, 'data-w-sync-target-value="#id_slug"') + # SEO title should be present in promote tab + self.assertContains( + response, "The name of the page displayed on search engine results" + ) + def test_create_simplepage_post(self): post_data = { "title": "New page!", diff --git a/wagtail/admin/tests/test_edit_handlers.py b/wagtail/admin/tests/test_edit_handlers.py index df261a2bbcc..6a2a99a607e 100644 --- a/wagtail/admin/tests/test_edit_handlers.py +++ b/wagtail/admin/tests/test_edit_handlers.py @@ -30,6 +30,7 @@ PublishingPanel, TabbedInterface, TitleFieldPanel, + expand_panel_list, extract_panel_definitions_from_model_class, get_form_for_model, ) @@ -1726,7 +1727,10 @@ def test_comments_disabled_setting(self): Test that the comment panel is missing if WAGTAILADMIN_COMMENTS_ENABLED=False """ self.assertFalse( - any(isinstance(panel, CommentPanel) for panel in Page.settings_panels) + any( + isinstance(panel, CommentPanel) + for panel in expand_panel_list(Page, Page.settings_panels) + ) ) form_class = Page.get_edit_handler().get_form_class() form = form_class() @@ -1737,7 +1741,10 @@ def test_comments_enabled_setting(self): Test that the comment panel is present by default """ self.assertTrue( - any(isinstance(panel, CommentPanel) for panel in Page.settings_panels) + any( + isinstance(panel, CommentPanel) + for panel in expand_panel_list(Page, Page.settings_panels) + ) ) form_class = Page.get_edit_handler().get_form_class() form = form_class() @@ -2024,7 +2031,10 @@ def test_publishing_panel_shown_by_default(self): Test that the publishing panel is present by default """ self.assertTrue( - any(isinstance(panel, PublishingPanel) for panel in Page.settings_panels) + any( + isinstance(panel, PublishingPanel) + for panel in expand_panel_list(Page, Page.settings_panels) + ) ) form_class = Page.get_edit_handler().get_form_class() form = form_class() diff --git a/wagtail/test/earlypage/__init__.py b/wagtail/test/earlypage/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/wagtail/test/earlypage/migrations/0001_initial.py b/wagtail/test/earlypage/migrations/0001_initial.py new file mode 100644 index 00000000000..6930a093318 --- /dev/null +++ b/wagtail/test/earlypage/migrations/0001_initial.py @@ -0,0 +1,37 @@ +# Generated by Django 5.1.4 on 2025-01-03 15:30 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ("wagtailcore", "0094_alter_page_locale"), + ] + + operations = [ + migrations.CreateModel( + name="EarlyPage", + fields=[ + ( + "page_ptr", + models.OneToOneField( + auto_created=True, + on_delete=django.db.models.deletion.CASCADE, + parent_link=True, + primary_key=True, + serialize=False, + to="wagtailcore.page", + ), + ), + ("intro", models.TextField(blank=True)), + ], + options={ + "abstract": False, + }, + bases=("wagtailcore.page",), + ), + ] diff --git a/wagtail/test/earlypage/migrations/__init__.py b/wagtail/test/earlypage/migrations/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/wagtail/test/earlypage/models.py b/wagtail/test/earlypage/models.py new file mode 100644 index 00000000000..476049bb854 --- /dev/null +++ b/wagtail/test/earlypage/models.py @@ -0,0 +1,14 @@ +# This module DOES NOT import from wagtail.admin - +# this tests that we are able to define Page models before wagtail.admin is loaded. + +from django.db import models + +from wagtail.models import Page + + +class EarlyPage(Page): + intro = models.TextField(blank=True) + + content_panels = Page.content_panels + [ + "intro", + ] diff --git a/wagtail/test/settings.py b/wagtail/test/settings.py index 42748212278..840f6f318b9 100644 --- a/wagtail/test/settings.py +++ b/wagtail/test/settings.py @@ -135,6 +135,9 @@ ) INSTALLED_APPS = [ + # Place wagtail.test.earlypage first, to test the behaviour of page models + # that are defined before wagtail.admin is loaded + "wagtail.test.earlypage", # Install wagtailredirects with its appconfig # There's nothing special about wagtailredirects, we just need to have one # app which uses AppConfigs to test that hooks load properly
null
null
wagtail
12,670
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index a6de5e45cc07..7313103766e6 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -14,6 +14,7 @@ Changelog * Allow plain strings in panel definitions as shorthand for `FieldPanel` / `InlinePanel` (Matt Westcott) * Only allow selection of valid new parents within the copy Page view (Mauro Soche) * Add `on_serve_page` hook to modify the serving chain of pages (Krystian Magdziarz, Dawid Bugajewski) + * Add support for `WAGTAIL_GRAVATAR_PROVIDER_URL` URLs with query string parameters (Ayaan Qadri, Guilhem Saurel) * Fix: Improve handling of translations for bulk page action confirmation messages (Matt Westcott) * Fix: Ensure custom rich text feature icons are correctly handled when provided as a list of SVG paths (Temidayo Azeez, Joel William, LB (Ben) Johnston) * Fix: Ensure manual edits to `StreamField` values do not throw an error (Stefan Hammer) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 8699bd687dce..e5bbc70f7129 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -861,6 +861,7 @@ * Harsh Dange * Mauro Soche * Krystian Magdziarz +* Guilhem Saurel ## Translators diff --git a/docs/reference/settings.md b/docs/reference/settings.md index 85f0ef7103c5..88381ab6b0c6 100644 --- a/docs/reference/settings.md +++ b/docs/reference/settings.md @@ -636,6 +636,14 @@ WAGTAIL_GRAVATAR_PROVIDER_URL = '//www.gravatar.com/avatar' If a user has not uploaded a profile picture, Wagtail will look for an avatar linked to their email address on gravatar.com. This setting allows you to specify an alternative provider such as like robohash.org, or can be set to `None` to disable the use of remote avatars completely. +Any provided query string will merge with the default parameters. For example, using the setting `//www.gravatar.com/avatar?d=robohash` will use the `robohash` override instead of the default `mp` (mystery person). The `s` parameter will be ignored as this is specified depending on location within the admin interface. + +See the [Gravatar images URL documentation](https://docs.gravatar.com/api/avatars/images/) for more details. + +```{versionchanged} 6.4 +Added query string merging. +``` + (wagtail_user_time_zones)= ### `WAGTAIL_USER_TIME_ZONES` diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 742b7fe8ead3..805108025fda 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -23,6 +23,7 @@ depth: 1 * Allow plain strings in panel definitions as shorthand for `FieldPanel` / `InlinePanel` (Matt Westcott) * Only allow selection of valid new parents within the copy Page view (Mauro Soche) * Add [`on_serve_page`](on_serve_page) hook to modify the serving chain of pages (Krystian Magdziarz, Dawid Bugajewski) + * Add support for [`WAGTAIL_GRAVATAR_PROVIDER_URL`](wagtail_gravatar_provider_url) URLs with query string parameters (Ayaan Qadri, Guilhem Saurel) ### Bug fixes diff --git a/wagtail/users/utils.py b/wagtail/users/utils.py index b3eee7970d07..9c4b59bc83f5 100644 --- a/wagtail/users/utils.py +++ b/wagtail/users/utils.py @@ -1,3 +1,5 @@ +from urllib.parse import parse_qs, urlparse, urlunparse + from django.conf import settings from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ @@ -25,11 +27,29 @@ def user_can_delete_user(current_user, user_to_delete): return True -def get_gravatar_url(email, size=50): - default = "mp" - size = ( - int(size) * 2 - ) # requested at retina size by default and scaled down at point of use with css +def get_gravatar_url(email, size=50, default_params={"d": "mp"}): + """ + See https://gravatar.com/site/implement/images/ for Gravatar image options. + + Example usage: + + .. code-block:: python + + # Basic usage + gravatar_url = get_gravatar_url('user@example.com') + + # Customize size and default image + gravatar_url = get_gravatar_url( + 'user@example.com', + size=100, + default_params={'d': 'robohash', 'f': 'y'} + ) + + Note: + If any parameter in ``default_params`` also exists in the provider URL, + it will be overridden by the provider URL's query parameter. + """ + gravatar_provider_url = getattr( settings, "WAGTAIL_GRAVATAR_PROVIDER_URL", "//www.gravatar.com/avatar" ) @@ -37,14 +57,26 @@ def get_gravatar_url(email, size=50): if (not email) or (gravatar_provider_url is None): return None - email_bytes = email.lower().encode("utf-8") - hash = safe_md5(email_bytes, usedforsecurity=False).hexdigest() - gravatar_url = "{gravatar_provider_url}/{hash}?{params}".format( - gravatar_provider_url=gravatar_provider_url.rstrip("/"), - hash=hash, - params=urlencode({"s": size, "d": default}), + parsed_url = urlparse(gravatar_provider_url) + + params = { + **default_params, + **(parse_qs(parsed_url.query or "")), + # requested at retina size by default and scaled down at point of use with css + "s": int(size) * 2, + } + + email_hash = safe_md5( + email.lower().encode("utf-8"), usedforsecurity=False + ).hexdigest() + + parsed_url = parsed_url._replace( + path=f"{parsed_url.path.rstrip('/')}/{email_hash}", + query=urlencode(params, doseq=True), ) + gravatar_url = urlunparse(parsed_url) + return gravatar_url
32417f9adca1d507bb4ca4880ee4d8879062de04
Add a third `default_params` parameter to the function that allows customizing URL parameters, with a default value of `{"d": "mp"}`, and rewrite the function to properly handle URL parsing and parameter merging.
The following is the text of a github issue and related comments for this repository: Enhance capabilities for `WAGTAIL_GRAVATAR_PROVIDER_URL` URL to support merging of URL params ### Is your proposal related to a problem? Currently, there is no simple way to [`WAGTAIL_GRAVATAR_PROVIDER_URL`](https://docs.wagtail.org/en/stable/reference/settings.html#wagtail-gravatar-provider-url) to support being given URL params. For example, setting the following; ```py WAGTAIL_GRAVATAR_PROVIDER_URL = '//www.gravatar.com/avatar?d=robohash' ``` Will result in the request being made to `http://www.gravatar.com/avatar?d=robohash/<the-hash>?s=50&d=mm` But this is not a valid Gravatar URL, it will not correctly hq dle the hash, it should be: `http://www.gravatar.com/avatar/<the-hash>?s=50&d=mm&d=robohash` If there are valid Gravatar email addresses, these would never show. ![Image](https://github.com/user-attachments/assets/da5b435e-b95a-464d-b9b0-85e1c3e0462c) ### Describe the solution you'd like The ideal solution would be to support smarter merging of these params with the existing params set by `get_gravatar_url`, while also making this function a bit more versatile. https://github.com/wagtail/wagtail/blob/c2676af857a41440e05e03038d85a540dcca3ce2/wagtail/users/utils.py#L28-L48 This could be updated to something like this rough idea, not sure if this will work but might be a good starting point. 1. Rework where the default/size are declared to closer to where we need them. 2. Parse the URL provided, allowing us to pull out and merge the query string, then re-build the URL while merging params allowing the params on the setting URL to override this 3. Still strip the last slash to support existing compatibility 4. Update the default to be `mp` as per the Gravatar docs, add docstring for reference to these docs 5. Add the reference to the settings documentation page https://docs.wagtail.org/en/stable/reference/settings.html#wagtail-gravatar-provider-url (using the appropriate MyST syntax to include docstrings OR just put the example within that settings section). Example update of `get_gravatar_url`: ```python from urllib.parse import parse_qs, urlparse # ... def get_gravatar_url(email, size=50, default_params={"d": "mm"}): """ See https://gravatar.com/site/implement/images/ for Gravatar image options ...put an example here with proper escaping ...reference this in the settings docs. """ gravatar_provider_url = getattr( settings, "WAGTAIL_GRAVATAR_PROVIDER_URL", "//www.gravatar.com/avatar" ) if (not email) or (gravatar_provider_url is None): return None # requested at retina size by default and scaled down at point of use with css size = int(size) * 2 url = urlparse(gravatar_provider_url) email_bytes = email.lower().encode("utf-8") hash = safe_md5(email_bytes, usedforsecurity=False).hexdigest() gravatar_url = "{base_url}/{hash}?{params}".format( gravatar_provider_url="".join(url[:3]).rstrip("/"), hash=hash, params={"z": size, **default_params, **parse_qs(url.query)}, ) return gravatar_url ``` This may not be the best solution, but it is a good starting point. ### Describe alternatives you've considered - At a minimum, we should support stripping params from the provided URL so that adding params does not break things. - Next best solution is preserving them by pulling them out, moving them back into the URL at the end. - However, as above, the ideal solution would be great to be able to support and be a more intuitive developer experience ### Additional context - Two PRs have attempted this, please look at them and also look at the comments/reviews, please only pick up this issue if you are willing to work through feedback, add unit tests and add documentation. - #11800 & #11077 ### Working on this - Anyone can contribute to this, it may make sense to do this other simpler issue first though - https://github.com/wagtail/wagtail/issues/12658 - The PR cannot be reviewed without unit tests and documentation first, if you are not sure on the approach, please add comments to this issue for discussion. - View our [contributing guidelines](https://docs.wagtail.org/en/latest/contributing/index.html), add a comment to the issue once you’re ready to start. Example updated usage: ```python # Basic usage gravatar_url = get_gravatar_url('user@example.com') # Customize size and default image gravatar_url = get_gravatar_url( 'user@example.com', size=100, default_params={'d': 'robohash', 'f': 'y'} ) ``` Note: If any parameter in ``default_params`` also exists in the provider URL, it will be overridden by the provider URL's query parameter. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/users/utils.py b/wagtail/users/utils.py index b3eee7970d07..9c4b59bc83f5 100644 --- a/wagtail/users/utils.py +++ b/wagtail/users/utils.py @@ -1,3 +1,5 @@ +from urllib.parse import parse_qs, urlparse, urlunparse + from django.conf import settings from django.utils.http import urlencode from django.utils.translation import gettext_lazy as _ @@ -25,11 +27,29 @@ def user_can_delete_user(current_user, user_to_delete): return True -def get_gravatar_url(email, size=50): - default = "mp" - size = ( - int(size) * 2 - ) # requested at retina size by default and scaled down at point of use with css +def get_gravatar_url(email, size=50, default_params={"d": "mp"}): + """ + See https://gravatar.com/site/implement/images/ for Gravatar image options. + + Example usage: + + .. code-block:: python + + # Basic usage + gravatar_url = get_gravatar_url('user@example.com') + + # Customize size and default image + gravatar_url = get_gravatar_url( + 'user@example.com', + size=100, + default_params={'d': 'robohash', 'f': 'y'} + ) + + Note: + If any parameter in ``default_params`` also exists in the provider URL, + it will be overridden by the provider URL's query parameter. + """ + gravatar_provider_url = getattr( settings, "WAGTAIL_GRAVATAR_PROVIDER_URL", "//www.gravatar.com/avatar" ) @@ -37,14 +57,26 @@ def get_gravatar_url(email, size=50): if (not email) or (gravatar_provider_url is None): return None - email_bytes = email.lower().encode("utf-8") - hash = safe_md5(email_bytes, usedforsecurity=False).hexdigest() - gravatar_url = "{gravatar_provider_url}/{hash}?{params}".format( - gravatar_provider_url=gravatar_provider_url.rstrip("/"), - hash=hash, - params=urlencode({"s": size, "d": default}), + parsed_url = urlparse(gravatar_provider_url) + + params = { + **default_params, + **(parse_qs(parsed_url.query or "")), + # requested at retina size by default and scaled down at point of use with css + "s": int(size) * 2, + } + + email_hash = safe_md5( + email.lower().encode("utf-8"), usedforsecurity=False + ).hexdigest() + + parsed_url = parsed_url._replace( + path=f"{parsed_url.path.rstrip('/')}/{email_hash}", + query=urlencode(params, doseq=True), ) + gravatar_url = urlunparse(parsed_url) + return gravatar_url
diff --git a/wagtail/admin/tests/ui/test_sidebar.py b/wagtail/admin/tests/ui/test_sidebar.py index f2e160144651..823064359c80 100644 --- a/wagtail/admin/tests/ui/test_sidebar.py +++ b/wagtail/admin/tests/ui/test_sidebar.py @@ -283,7 +283,7 @@ def test_adapt(self): ], { "name": user.first_name or user.get_username(), - "avatarUrl": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=100&d=mp", + "avatarUrl": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?d=mp&s=100", }, ], }, diff --git a/wagtail/users/tests/test_utils.py b/wagtail/users/tests/test_utils.py new file mode 100644 index 000000000000..8d0e58b21d28 --- /dev/null +++ b/wagtail/users/tests/test_utils.py @@ -0,0 +1,76 @@ +from django.test import TestCase, override_settings + +from wagtail.users.utils import get_gravatar_url + + +class TestGravatar(TestCase): + def test_gravatar_default(self): + """Test with the default settings""" + self.assertEqual( + get_gravatar_url("something@example.com"), + "//www.gravatar.com/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&s=100", + ) + + def test_gravatar_custom_size(self): + """Test with a custom size (note that the size will be doubled)""" + self.assertEqual( + get_gravatar_url("something@example.com", size=100), + "//www.gravatar.com/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&s=200", + ) + + @override_settings( + WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar?d=robohash&s=200" + ) + def test_gravatar_params_that_overlap(self): + """ + Test with params that overlap with default s (size) and d (default_image) + Also test the `s` is not overridden by the provider URL's query parameters. + """ + self.assertEqual( + get_gravatar_url("something@example.com", size=80), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=robohash&s=160", + ) + + @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar?f=y") + def test_gravatar_params_that_dont_overlap(self): + """Test with params that don't default `s (size)` and `d (default_image)`""" + self.assertEqual( + get_gravatar_url("something@example.com"), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&f=y&s=100", + ) + + @override_settings( + WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar?d=robohash&f=y" + ) + def test_gravatar_query_params_override_default_params(self): + """Test that query parameters of `WAGTAIL_GRAVATAR_PROVIDER_URL` override default_params""" + self.assertEqual( + get_gravatar_url( + "something@example.com", default_params={"d": "monsterid"} + ), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=robohash&f=y&s=100", + ) + + @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar/") + def test_gravatar_trailing_slash(self): + """Test with a trailing slash in the URL""" + self.assertEqual( + get_gravatar_url("something@example.com"), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&s=100", + ) + + @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar") + def test_gravatar_no_trailing_slash(self): + """Test with no trailing slash in the URL""" + self.assertEqual( + get_gravatar_url("something@example.com"), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&s=100", + ) + + @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar?") + def test_gravatar_trailing_question_mark(self): + """Test with a trailing question mark in the URL""" + self.assertEqual( + get_gravatar_url("something@example.com"), + "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=mp&s=100", + )
null
null
wagtail
12,622
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 464edbb79ec8..800be03010b3 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -22,6 +22,7 @@ Changelog * Fix: Prevent out-of-order migrations from skipping creation of image/document choose permissions (Matt Westcott) * Fix: Use correct connections on multi-database setups in database search backends (Jake Howard) * Fix: Ensure Cloudfront cache invalidation is called with a list, for compatibility with current botocore versions (Jake Howard) + * Fix: Show the correct privacy status in the sidebar when creating a new page (Joel William) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) * Docs: Move the tags documentation to standalone advanced topic, instead of being inside the reference/pages section (Srishti Jaiswal) diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 3ac28a05c9a6..d313169011de 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -35,6 +35,7 @@ depth: 1 * Prevent out-of-order migrations from skipping creation of image/document choose permissions (Matt Westcott) * Use correct connections on multi-database setups in database search backends (Jake Howard) * Ensure Cloudfront cache invalidation is called with a list, for compatibility with current botocore versions (Jake Howard) + * Show the correct privacy status in the sidebar when creating a new page (Joel William) ### Documentation diff --git a/wagtail/admin/templates/wagtailadmin/shared/side_panels/includes/status/privacy.html b/wagtail/admin/templates/wagtailadmin/shared/side_panels/includes/status/privacy.html index 88ec71393e44..7af790c880f2 100644 --- a/wagtail/admin/templates/wagtailadmin/shared/side_panels/includes/status/privacy.html +++ b/wagtail/admin/templates/wagtailadmin/shared/side_panels/includes/status/privacy.html @@ -2,7 +2,7 @@ {% load i18n wagtailadmin_tags %} {% block content %} - {% test_page_is_public page as is_public %} + {% if page.id %}{% test_page_is_public page as is_public %}{% else %}{% test_page_is_public parent_page as is_public %}{% endif %} {# The swap between public and private text is done using JS inside of privacy-switch.js when the response from the modal comes back #} <div class="{% if not is_public %}w-hidden{% endif %}" data-privacy-sidebar-public> diff --git a/wagtail/admin/ui/side_panels.py b/wagtail/admin/ui/side_panels.py index 2aa6167652e7..ddd064cd6a76 100644 --- a/wagtail/admin/ui/side_panels.py +++ b/wagtail/admin/ui/side_panels.py @@ -241,6 +241,7 @@ def get_context_data(self, parent_context): class PageStatusSidePanel(StatusSidePanel): def __init__(self, *args, **kwargs): + self.parent_page = kwargs.pop("parent_page", None) super().__init__(*args, **kwargs) if self.object.pk: self.usage_url = reverse("wagtailadmin_pages:usage", args=(self.object.pk,)) @@ -272,6 +273,9 @@ def get_context_data(self, parent_context): context = super().get_context_data(parent_context) page = self.object + if self.parent_page: + context["parent_page"] = self.parent_page + if page.id: context.update( { diff --git a/wagtail/admin/views/pages/create.py b/wagtail/admin/views/pages/create.py index 172f258969f1..c378ad1faaec 100644 --- a/wagtail/admin/views/pages/create.py +++ b/wagtail/admin/views/pages/create.py @@ -358,6 +358,7 @@ def get_side_panels(self): show_schedule_publishing_toggle=self.form.show_schedule_publishing_toggle, locale=self.locale, translations=self.translations, + parent_page=self.parent_page, ), ] if self.page.is_previewable(): diff --git a/wagtail/admin/views/pages/edit.py b/wagtail/admin/views/pages/edit.py index 98e6dafda875..5dfe4dab48e6 100644 --- a/wagtail/admin/views/pages/edit.py +++ b/wagtail/admin/views/pages/edit.py @@ -868,6 +868,7 @@ def get_side_panels(self): scheduled_object=self.scheduled_page, locale=self.locale, translations=self.translations, + parent_page=self.page.get_parent(), ), ] if self.page.is_previewable():
7566fb84e0709b9dd1139161c244ea5c49d3b4c0
Store the parent page in the panel instance and add it to the context if available.
The following is the text of a github issue and related comments for this repository: New page shows incorrect privacy info <!-- Found a bug? Please fill out the sections below. 👍 --> ### Issue Summary When creating a new page that is a child of a private page the info section shows "Visible to all" but it should be "Private" ![image](https://github.com/user-attachments/assets/c46cf09b-4f3f-4fb3-9680-9cd0f456fc93) <!-- A summary of the issue. --> ### Steps to Reproduce - In wagtail bakery create a new page as a child of a private page. - Click the status icon, see the privacy option Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead? - It should show something similar to the edit view which says "Private". - I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes ### Technical details - Python version: 3.12.5 - Django version: 5.0.8 - Wagtail version: 6.2a0 (dev) - Browser version: Chrome 128. ### Working on this <!-- Do you have thoughts on skills needed? Are you keen to work on this yourself once the issue has been accepted? Please let us know here. --> Anyone can contribute to this. View our [contributing guidelines](https://docs.wagtail.org/en/latest/contributing/index.html), add a comment to the issue once you’re ready to start. I can confirm this problem exists. From some quick digging it appears that within the tag def test_page_is_public(context, page): there is no page.path available when the page is not yet created (which makes sense). wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py Lines 276 to 279 in 09a9261 is_private = any( page.path.startswith(restricted_path) for restricted_path in context["request"].all_page_view_restriction_paths ) A potential fix might be to either just not show this panel when creating new pages in wagtail/admin/ui/side_panels.py. class PageStatusSidePanel(StatusSidePanel): # ... def get_status_templates(self, context): templates = super().get_status_templates(context) # only inject the privacy status if the page exists (not for create page views) if self.object.id: templates.insert( -1, "wagtailadmin/shared/side_panels/includes/status/privacy.html" ) return templates Another potential fix would be to pass in a way to access the parent page to the template, this appears to be a bit of a larger change. This is probably the preferred approach though, as we have the data, just need to pass it through. wagtail/admin/templates/wagtailadmin/shared/side_panels/includes/status/privacy.html {% extends 'wagtailadmin/shared/side_panels/includes/action_list_item.html' %} {% load i18n wagtailadmin_tags %} {% block content %} {% if page.id %}{% test_page_is_public page as is_public %}{% else %}{% test_page_is_public parent_page as is_public %}{% endif %} Then, we need to pass the parent_page through from wagtail/admin/views/pages/create.py in the CreateView.get_side_panels method, then pass it through to the context in PageStatusSidePanel. We may need to also do the same for the EditView. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/admin/ui/side_panels.py b/wagtail/admin/ui/side_panels.py index 2aa6167652e7..ddd064cd6a76 100644 --- a/wagtail/admin/ui/side_panels.py +++ b/wagtail/admin/ui/side_panels.py @@ -241,6 +241,7 @@ def get_context_data(self, parent_context): class PageStatusSidePanel(StatusSidePanel): def __init__(self, *args, **kwargs): + self.parent_page = kwargs.pop("parent_page", None) super().__init__(*args, **kwargs) if self.object.pk: self.usage_url = reverse("wagtailadmin_pages:usage", args=(self.object.pk,)) @@ -272,6 +273,9 @@ def get_context_data(self, parent_context): context = super().get_context_data(parent_context) page = self.object + if self.parent_page: + context["parent_page"] = self.parent_page + if page.id: context.update( {
diff --git a/wagtail/admin/tests/pages/test_create_page.py b/wagtail/admin/tests/pages/test_create_page.py index 6f5b1d5f57ea..6ad7f6c6df8d 100644 --- a/wagtail/admin/tests/pages/test_create_page.py +++ b/wagtail/admin/tests/pages/test_create_page.py @@ -9,7 +9,13 @@ from django.utils import timezone from django.utils.translation import gettext_lazy as _ -from wagtail.models import GroupPagePermission, Locale, Page, Revision +from wagtail.models import ( + GroupPagePermission, + Locale, + Page, + PageViewRestriction, + Revision, +) from wagtail.signals import page_published from wagtail.test.testapp.models import ( BusinessChild, @@ -1975,3 +1981,80 @@ def test_comments_disabled(self): self.assertEqual("page-edit-form", form["id"]) self.assertIn("w-init", form["data-controller"]) self.assertEqual("", form["data-w-init-event-value"]) + + +class TestCreateViewChildPagePrivacy(WagtailTestUtils, TestCase): + def setUp(self): + self.login() + + self.homepage = Page.objects.get(id=2) + + self.private_parent_page = self.homepage.add_child( + instance=SimplePage( + title="Private Parent page", + content="hello", + live=True, + ) + ) + + PageViewRestriction.objects.create( + page=self.private_parent_page, + restriction_type="password", + password="password123", + ) + + self.private_child_page = self.private_parent_page.add_child( + instance=SimplePage( + title="child page", + content="hello", + live=True, + ) + ) + + self.public_parent_page = self.homepage.add_child( + instance=SimplePage( + title="Public Parent page", + content="hello", + live=True, + ) + ) + + self.public_child_page = self.public_parent_page.add_child( + instance=SimplePage( + title="public page", + content="hello", + live=True, + ) + ) + + def test_sidebar_private(self): + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "simplepage", self.private_child_page.id), + ) + ) + + self.assertEqual(response.status_code, 200) + + self.assertContains(response, '<div class="" data-privacy-sidebar-private>') + + self.assertContains( + response, '<div class="w-hidden" data-privacy-sidebar-public>' + ) + + def test_sidebar_public(self): + response = self.client.get( + reverse( + "wagtailadmin_pages:add", + args=("tests", "simplepage", self.public_child_page.id), + ) + ) + + self.assertEqual(response.status_code, 200) + + self.assertContains( + response, '<div class="w-hidden" data-privacy-sidebar-private>' + ) + + self.assertContains(response, '<div class="" data-privacy-sidebar-public>')
null
null
wagtail
12,671
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 98757878477c..04b31ec25ef2 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -12,6 +12,7 @@ Changelog * Limit tags autocompletion to 10 items and add delay to avoid performance issues with large number of matching tags (Aayushman Singh) * Add the ability to restrict what types of requests a Pages supports via `allowed_http_methods` (Andy Babic) * Allow plain strings in panel definitions as shorthand for `FieldPanel` / `InlinePanel` (Matt Westcott) + * Only allow selection of valid new parents within the copy Page view (Mauro Soche) * Fix: Improve handling of translations for bulk page action confirmation messages (Matt Westcott) * Fix: Ensure custom rich text feature icons are correctly handled when provided as a list of SVG paths (Temidayo Azeez, Joel William, LB (Ben) Johnston) * Fix: Ensure manual edits to `StreamField` values do not throw an error (Stefan Hammer) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3a93220731b3..e2d1a4eb0550 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -859,6 +859,7 @@ * Strapchay * Alex Fulcher * Harsh Dange +* Mauro Soche ## Translators diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index b043aab52ddb..ff3e4550e456 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -21,6 +21,7 @@ depth: 1 * Limit tags autocompletion to 10 items and add delay to avoid performance issues with large number of matching tags (Aayushman Singh) * Add the ability to restrict what types of requests a Pages supports via [`allowed_http_methods`](#wagtail.models.Page.allowed_http_methods) (Andy Babic) * Allow plain strings in panel definitions as shorthand for `FieldPanel` / `InlinePanel` (Matt Westcott) + * Only allow selection of valid new parents within the copy Page view (Mauro Soche) ### Bug fixes diff --git a/wagtail/admin/forms/pages.py b/wagtail/admin/forms/pages.py index 47e5f18cd9a6..a7a930ac7871 100644 --- a/wagtail/admin/forms/pages.py +++ b/wagtail/admin/forms/pages.py @@ -30,7 +30,11 @@ def __init__(self, *args, **kwargs): self.fields["new_parent_page"] = forms.ModelChoiceField( initial=self.page.get_parent(), queryset=Page.objects.all(), - widget=widgets.AdminPageChooser(can_choose_root=True, user_perms="copy_to"), + widget=widgets.AdminPageChooser( + target_models=self.page.specific_class.allowed_parent_page_models(), + can_choose_root=True, + user_perms="copy_to", + ), label=_("New parent page"), help_text=_("This copy will be a child of this given parent page."), )
547e4d3731a6492eb4b9d088ee268720224713d1
Add target models to the page chooser to only allow selection of valid parent page types based on the page's allowed parent models.
The following is the text of a github issue and related comments for this repository: Improve page chooser (widgets.AdminChooser) when copying a page ### Is your proposal related to a problem? When a user is in the form to copy a page (`CopyForm`), some pages appear as available destinations when in fact it is not a possible destination due to the hierarchy of the page to copy. Currently playing with the `bakarydemo` project, I am copying a `location` type page and the `widgets.AdminPageChooser` visually show and lets select other types of pages as possible destinations. At the end of the flow, it throws an error notification that may not be too clear. ![Screenshot 2024-02-05 at 5 13 27 PM](https://github.com/wagtail/wagtail/assets/19751214/511caeb7-712a-4310-b83e-9f1aeec6df2d) ![Screenshot 2024-02-05 at 5 12 23 PM](https://github.com/wagtail/wagtail/assets/19751214/08c8b4fb-0d6d-479c-8a79-1b3c41283062) - error text "Sorry, you do not have permission to access this area" ### Describe the solution you'd like I would like the page chooser to gray out the page types that do not follow the hierarchy. My suggestion is to pass the `target_models` parameter to `widgets.AdminPageChooser` on [CopyForm](https://github.com/wagtail/wagtail/blob/stable/5.2.x/wagtail/admin/forms/pages.py#L33), which allows us to specify the types of pages that can only be selectable. In this case, I would suggest passing as the value of this parameter the value returned by the function `allowed_parent_page_models` ```python self.fields["new_parent_page"] = forms.ModelChoiceField( initial=self.page.get_parent(), queryset=Page.objects.all(), widget=widgets.AdminPageChooser(target_models=self.page.specific_class.allowed_parent_page_models(), can_choose_root=True, user_perms="copy_to"), label=_("New parent page"), help_text=_("This copy will be a child of this given parent page."), ) ``` Following the example on `bakerydemo` and taking as reference the mentioned change, the page selector would look like this ![Screenshot 2024-02-05 at 5 31 06 PM](https://github.com/wagtail/wagtail/assets/19751214/573dd04a-8567-43af-aa9b-4842f404b712) ### Working on this <!-- Do you have thoughts on skills needed? Are you keen to work on this yourself once the issue has been accepted? Please let us know here. --> Anyone can contribute to this. View our [contributing guidelines](https://docs.wagtail.org/en/latest/contributing/index.html), add a comment to the issue once you’re ready to start. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/admin/forms/pages.py b/wagtail/admin/forms/pages.py index 47e5f18cd9a6..a7a930ac7871 100644 --- a/wagtail/admin/forms/pages.py +++ b/wagtail/admin/forms/pages.py @@ -30,7 +30,11 @@ def __init__(self, *args, **kwargs): self.fields["new_parent_page"] = forms.ModelChoiceField( initial=self.page.get_parent(), queryset=Page.objects.all(), - widget=widgets.AdminPageChooser(can_choose_root=True, user_perms="copy_to"), + widget=widgets.AdminPageChooser( + target_models=self.page.specific_class.allowed_parent_page_models(), + can_choose_root=True, + user_perms="copy_to", + ), label=_("New parent page"), help_text=_("This copy will be a child of this given parent page."), )
diff --git a/wagtail/admin/tests/test_page_chooser.py b/wagtail/admin/tests/test_page_chooser.py index 5ec5cfbdba00..eaa52d5b5199 100644 --- a/wagtail/admin/tests/test_page_chooser.py +++ b/wagtail/admin/tests/test_page_chooser.py @@ -249,6 +249,35 @@ def test_with_multiple_page_types(self): self.assertIn(event_page.id, pages) self.assertTrue(pages[self.child_page.id].can_choose) + def test_with_multiple_specific_page_types_display_warning(self): + # Add a page that is not a SimplePage + event_page = EventPage( + title="event", + location="the moon", + audience="public", + cost="free", + date_from="2001-01-01", + ) + self.root_page.add_child(instance=event_page) + + # Send request + response = self.get({"page_type": "tests.simplepage,tests.eventpage"}) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.context["page_type_names"], ["Simple page", "Event page"] + ) + + html = response.json().get("html") + expected = """ + <p class="help-block help-warning"> + <svg class="icon icon-warning icon" aria-hidden="true"><use href="#icon-warning"></use></svg> + Only the following page types may be chosen for this field: Simple page, Event page. Search results will exclude pages of other types. + </p> + """ + + self.assertTagInHTML(expected, html) + def test_with_unknown_page_type(self): response = self.get({"page_type": "foo.bar"}) self.assertEqual(response.status_code, 404)
diff --git a/wagtail/admin/forms/pages.py b/wagtail/admin/forms/pages.py index 47e5f18cd9a6..a7a930ac7871 100644 --- a/wagtail/admin/forms/pages.py +++ b/wagtail/admin/forms/pages.py @@ -30,7 +30,11 @@ def __init__(self, *args, **kwargs): widget=
diff --git a/wagtail/admin/forms/pages.py b/wagtail/admin/forms/pages.py index 47e5f18cd9a6..a7a930ac7871 100644 --- a/wagtail/admin/forms/pages.py +++ b/wagtail/admin/forms/pages.py @@ -30,7 +30,11 @@ def __init__(self, *args, **kwargs): self.fields["new_parent_page"] = forms.ModelChoiceField( initial=self.page.get_parent(), queryset=Page.objects.all(), - widget=widgets.AdminPageChooser(can_choose_root=True, user_perms="copy_to"), + widget=widgets.AdminPageChooser( + target_models=self.page.specific_class.allowed_parent_page_models(), + can_choose_root=True, + user_perms="copy_to", + ), label=_("New parent page"), help_text=_("This copy will be a child of this given parent page."), )
wagtail
12,569
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index d73e9511bea8..6c4de8502305 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -52,6 +52,8 @@ Changelog * Maintenance: Various performance optimizations to page publishing (Jake Howard) * Maintenance: Remove unnecessary DOM canvas.toBlob polyfill (LB (Ben) Johnston) * Maintenance: Ensure Storybook core files are correctly running through Eslint (LB (Ben) Johnston) + * Maintenance: Add a new Stimulus `ZoneController` (`w-zone`) to support dynamic class name changes & event handling on container elements (Ayaan Qadri) + * Maintenance: Migrate jQuery class toggling & drag/drop event handling within the multiple upload views to the Stimulus ZoneController usage (Ayaan Qadri) 6.3.1 (19.11.2024) diff --git a/client/src/controllers/ZoneController.stories.js b/client/src/controllers/ZoneController.stories.js new file mode 100644 index 000000000000..d1a33aa8bd69 --- /dev/null +++ b/client/src/controllers/ZoneController.stories.js @@ -0,0 +1,46 @@ +import React from 'react'; + +import { StimulusWrapper } from '../../storybook/StimulusWrapper'; +import { ZoneController } from './ZoneController'; + +export default { + title: 'Stimulus / ZoneController', + argTypes: { + debug: { + control: 'boolean', + defaultValue: false, + }, + }, +}; + +const definitions = [ + { + identifier: 'w-zone', + controllerConstructor: ZoneController, + }, +]; + +const Template = ({ debug = false }) => ( + <StimulusWrapper debug={debug} definitions={definitions}> + <div + className="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="hovered" + data-action=" + dragover->w-zone#activate:prevent + dragleave->w-zone#deactivate + dragend->w-zone#deactivate + drop->w-zone#deactivate:prevent + " + > + Drag something here + </div> + + <p> + Drag an item over the box, and drop it to see class activation and + deactivation in action. + </p> + </StimulusWrapper> +); + +export const Base = Template.bind({}); diff --git a/client/src/controllers/ZoneController.ts b/client/src/controllers/ZoneController.ts new file mode 100644 index 000000000000..54d890fe3d2f --- /dev/null +++ b/client/src/controllers/ZoneController.ts @@ -0,0 +1,76 @@ +import { Controller } from '@hotwired/stimulus'; +import { debounce } from '../utils/debounce'; + +enum ZoneMode { + Active = 'active', + Inactive = '', +} + +/** + * Enables the controlled element to respond to specific user interactions + * by adding or removing CSS classes dynamically. + * + * @example + * ```html + * <div + * data-controller="w-zone" + * data-w-zone-active-class="hovered active" + * data-action="dragover->w-zone#activate dragleave->w-zone#deactivate" + * > + * Drag files here and see the effect. + * </div> + * ``` + */ +export class ZoneController extends Controller { + static classes = ['active']; + + static values = { + delay: { type: Number, default: 0 }, + mode: { type: String, default: ZoneMode.Inactive }, + }; + + /** Tracks the current mode for this zone. */ + declare modeValue: ZoneMode; + + /** Classes to append when the mode is active & remove when inactive. */ + declare readonly activeClasses: string[]; + /** Delay, in milliseconds, to use when debouncing the mode updates. */ + declare readonly delayValue: number; + + initialize() { + const delayValue = this.delayValue; + if (delayValue <= 0) return; + this.activate = debounce(this.activate.bind(this), delayValue); + // Double the delay for deactivation to prevent flickering. + this.deactivate = debounce(this.deactivate.bind(this), delayValue * 2); + } + + activate() { + this.modeValue = ZoneMode.Active; + } + + deactivate() { + this.modeValue = ZoneMode.Inactive; + } + + modeValueChanged(current: ZoneMode) { + const activeClasses = this.activeClasses; + + if (!activeClasses.length) return; + + if (current === ZoneMode.Active) { + this.element.classList.add(...activeClasses); + } else { + this.element.classList.remove(...activeClasses); + } + } + + /** + * Intentionally does nothing. + * + * Useful for attaching data-action to leverage the built in + * Stimulus options without needing any extra functionality. + * e.g. preventDefault (`:prevent`) and stopPropagation (`:stop`). + */ + noop() {} +} diff --git a/client/src/controllers/index.ts b/client/src/controllers/index.ts index 0f6b0fdac9f5..40449cc69678 100644 --- a/client/src/controllers/index.ts +++ b/client/src/controllers/index.ts @@ -30,6 +30,7 @@ import { TeleportController } from './TeleportController'; import { TooltipController } from './TooltipController'; import { UnsavedController } from './UnsavedController'; import { UpgradeController } from './UpgradeController'; +import { ZoneController } from './ZoneController'; /** * Important: Only add default core controllers that should load with the base admin JS bundle. @@ -67,4 +68,5 @@ export const coreControllerDefinitions: Definition[] = [ { controllerConstructor: TooltipController, identifier: 'w-tooltip' }, { controllerConstructor: UnsavedController, identifier: 'w-unsaved' }, { controllerConstructor: UpgradeController, identifier: 'w-upgrade' }, + { controllerConstructor: ZoneController, identifier: 'w-zone' }, ]; diff --git a/client/src/entrypoints/admin/core.js b/client/src/entrypoints/admin/core.js index 77bc30639572..63fb628ddee0 100644 --- a/client/src/entrypoints/admin/core.js +++ b/client/src/entrypoints/admin/core.js @@ -1,4 +1,3 @@ -import $ from 'jquery'; import * as StimulusModule from '@hotwired/stimulus'; import { Icon, Portal } from '../..'; @@ -58,14 +57,3 @@ window.MultipleChooserPanel = MultipleChooserPanel; */ window.URLify = (str, numChars = 255, allowUnicode = false) => urlify(str, { numChars, allowUnicode }); - -$(() => { - /* Dropzones */ - $('.drop-zone') - .on('dragover', function onDragOver() { - $(this).addClass('hovered'); - }) - .on('dragleave dragend drop', function onDragLeave() { - $(this).removeClass('hovered'); - }); -}); diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index c24be86591c3..c21f405d9ada 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -71,6 +71,8 @@ depth: 1 * Various performance optimizations to page publishing (Jake Howard) * Remove unnecessary DOM canvas.toBlob polyfill (LB (Ben) Johnston) * Ensure Storybook core files are correctly running through Eslint (LB (Ben) Johnston) + * Add a new Stimulus `ZoneController` (`w-zone`) to support dynamic class name changes & event handling on container elements (Ayaan Qadri) + * Migrate jQuery class toggling & drag/drop event handling within the multiple upload views to the Stimulus ZoneController usage (Ayaan Qadri) ## Upgrade considerations - changes affecting all projects diff --git a/wagtail/documents/static_src/wagtaildocs/js/add-multiple.js b/wagtail/documents/static_src/wagtaildocs/js/add-multiple.js index fabf2550c3ec..1dfff9e524fd 100644 --- a/wagtail/documents/static_src/wagtaildocs/js/add-multiple.js +++ b/wagtail/documents/static_src/wagtaildocs/js/add-multiple.js @@ -1,9 +1,4 @@ $(function () { - // prevents browser default drag/drop - $(document).on('drop dragover', function (e) { - e.preventDefault(); - }); - $('#fileupload').fileupload({ dataType: 'html', sequentialUploads: true, diff --git a/wagtail/documents/templates/wagtaildocs/multiple/add.html b/wagtail/documents/templates/wagtaildocs/multiple/add.html index 2b2becfd51be..dcab9aa31d5c 100644 --- a/wagtail/documents/templates/wagtaildocs/multiple/add.html +++ b/wagtail/documents/templates/wagtaildocs/multiple/add.html @@ -10,7 +10,13 @@ {% endblock %} {% block main_content %} - <div class="drop-zone w-mt-8"> + <div + class="drop-zone w-mt-8" + data-controller="w-zone" + data-action="dragover@document->w-zone#noop:prevent drop@document->w-zone#noop:prevent dragover->w-zone#activate drop->w-zone#deactivate dragleave->w-zone#deactivate dragend->w-zone#deactivate" + data-w-zone-active-class="hovered" + data-w-zone-delay-value="10" + > <p>{% trans "Drag and drop documents into this area to upload immediately." %}</p> <p>{{ help_text }}</p> diff --git a/wagtail/images/static_src/wagtailimages/js/add-multiple.js b/wagtail/images/static_src/wagtailimages/js/add-multiple.js index 7255bf2f28ff..35608cdb1fc4 100644 --- a/wagtail/images/static_src/wagtailimages/js/add-multiple.js +++ b/wagtail/images/static_src/wagtailimages/js/add-multiple.js @@ -1,9 +1,4 @@ $(function () { - // prevents browser default drag/drop - $(document).on('drop dragover', function (e) { - e.preventDefault(); - }); - $('#fileupload').fileupload({ dataType: 'html', sequentialUploads: true, diff --git a/wagtail/images/templates/wagtailimages/multiple/add.html b/wagtail/images/templates/wagtailimages/multiple/add.html index 0fb1c6574c34..e7accfb35436 100644 --- a/wagtail/images/templates/wagtailimages/multiple/add.html +++ b/wagtail/images/templates/wagtailimages/multiple/add.html @@ -10,7 +10,13 @@ {% endblock %} {% block main_content %} - <div class="drop-zone w-mt-8"> + <div + class="drop-zone w-mt-8" + data-controller="w-zone" + data-action="dragover@document->w-zone#noop:prevent drop@document->w-zone#noop:prevent dragover->w-zone#activate drop->w-zone#deactivate dragleave->w-zone#deactivate dragend->w-zone#deactivate" + data-w-zone-active-class="hovered" + data-w-zone-delay-value="10" + > <p>{% trans "Drag and drop images into this area to upload immediately." %}</p> <p>{{ help_text }}</p>
b9575f3498bba69fa2a8f53be110ec11ea3746f0
Add drag and drop event handling to the document upload zone, showing the "hovered" class during dragover with a 10ms delay, and prevent default browser drag/drop behavior.
The following is the text of a github issue and related comments for this repository: 🎛️ Create a new `ZoneController` to remove reliance on jQuery for toggling classes based on DOM events ### Is your proposal related to a problem? Currently we use jQuery for common behaviour such as 'add this class when hovered' or 'remove this class when event fires', these are common use cases that would be great candidates for our Stimulus migration. As a start, we should replace this specific jQuery usage with a new Stimulus controller. https://github.com/wagtail/wagtail/blob/246f3c7eb542be2081556bf5334bc22256776bf4/client/src/entrypoints/admin/core.js#L62-L71 ### Describe the solution you'd like Introduce a new Stimulus controller (calling this `ZoneController` for now, better names can be suggested), that allows us to use events to add/remove classes declaratively within HTML. We could remove the above referenced code in `core.js` and then update the HTML in [`wagtail/documents/templates/wagtaildocs/multiple/add.html`](https://github.com/wagtail/wagtail/blob/main/wagtail/images/templates/wagtaildocs/multiple/add.html) & [`wagtail/images/templates/wagtailimages/multiple/add.html`](https://github.com/wagtail/wagtail/blob/main/wagtail/images/templates/wagtailimages/multiple/add.html). > This is used in the multiple upload views for both images & documents. ![Image](https://github.com/user-attachments/assets/e3168e75-47cc-4918-a4f6-eca513150738) Finally, we could probably also remove the need for the `preventDefault` calls in both JS variations. This can be done on the controller instead. https://github.com/wagtail/wagtail/blob/246f3c7eb542be2081556bf5334bc22256776bf4/wagtail/documents/static_src/wagtaildocs/js/add-multiple.js#L2-L5 e.g. ```html {% block main_content %} <div class="drop-zone w-mt-8" data-controller="w-zone" data-w-zone-active-class="hovered" data-action="dragover->w-zone#activate:prevent dragleave->w-zone#deactivate dragend->w-zone#deactivate drop->w-zone#deactivate:prevent"> ``` #### Example controller Below is a starting controller implementation (not tested) that shows example usage. ```ts import { Controller } from '@hotwired/stimulus'; /** * Adds the ability for a zone (the controlled element) to be activated * or deactivated, allowing for dynamic classes triggered by events. * * @example - add .hovered when dragging over the element * ```html * <div data-controller="w-zone" data-w-zone-active-class="hovered" data-action="dragover->w-zone#activate dragleave->w-zone#deactivate dragend->w-zone#deactivate drop->w-zone#deactivate"> * ... drop zone * </div> * ``` * * @example - add .visible when the DOM is ready for interaction, removing .hidden * ```html * <div class="hidden" data-controller="w-zone" data-w-zone-inactive-class="hidden" data-w-zone-active-class="visible" data-action="load@window->w-zone#activate"> * ... shows as visible when ready to interact with * </div> * ``` */ export class ActionController extends Controller<HTMLElement> { static classes = ['active', 'inactive']; declare activeClasses: string[]; declare inactiveClasses: string[]; connect() { this.dispatch('ready', { cancelable: false }); // note: This is useful as a common pattern, allows the controller to change itself when connected } activate() { this.element.classList.removethis.activeClasses); this.element.classList.add(...this.inactiveClasses); } deactivate() { this.element.classList.remove(...this.inactiveClasses); this.element.classList.add(...this.activeClasses); } } ``` ### Describe alternatives you've considered * For this specific jQuery, we could just 'move' it around, as per https://github.com/wagtail/wagtail/pull/12497 - but this felt like a bad approach as we eventually do want to remove jQuery. ### Additional context * This is part of the ongoing Stimulus migration as per https://github.com/wagtail/rfcs/pull/78 * See the `client/src/controllers/` for examples of unit tests and other usage. * This could be further leveraged in a few places (e.g. `image-url-generator`) and also potentially be enhanced to support more than just two states (active/inactive). ### Working on this Ensure that the PR includes a full unit test suite, adoption in the HTML/removal of referenced jQuery in `core.js` and a Storybook story. * Anyone can contribute to this, please read the Stimulus docs in full if you have not already done so https://stimulus.hotwired.dev/ * Please include the removal of the `preventDefault` in `wagtail/documents/static_src/wagtaildocs/js/add-multiple.js` & `wagtail/images/static_src/wagtailimages/js/add-multiple.js` also * Ensure all behaviour across images/docs is correctly manually tested. * Please review our contributing guidelines specifically for Stimulus https://docs.wagtail.org/en/stable/contributing/ui_guidelines.html#stimulus * View our [contributing guidelines](https://docs.wagtail.org/en/latest/contributing/index.html), add a comment to the issue once you’re ready to start. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/documents/templates/wagtaildocs/multiple/add.html b/wagtail/documents/templates/wagtaildocs/multiple/add.html index 2b2becfd51be..dcab9aa31d5c 100644 --- a/wagtail/documents/templates/wagtaildocs/multiple/add.html +++ b/wagtail/documents/templates/wagtaildocs/multiple/add.html @@ -10,7 +10,13 @@ {% endblock %} {% block main_content %} - <div class="drop-zone w-mt-8"> + <div + class="drop-zone w-mt-8" + data-controller="w-zone" + data-action="dragover@document->w-zone#noop:prevent drop@document->w-zone#noop:prevent dragover->w-zone#activate drop->w-zone#deactivate dragleave->w-zone#deactivate dragend->w-zone#deactivate" + data-w-zone-active-class="hovered" + data-w-zone-delay-value="10" + > <p>{% trans "Drag and drop documents into this area to upload immediately." %}</p> <p>{{ help_text }}</p>
diff --git a/client/src/controllers/ZoneController.test.js b/client/src/controllers/ZoneController.test.js new file mode 100644 index 000000000000..238798c0af8a --- /dev/null +++ b/client/src/controllers/ZoneController.test.js @@ -0,0 +1,169 @@ +import { Application } from '@hotwired/stimulus'; +import { ZoneController } from './ZoneController'; + +jest.useFakeTimers(); + +describe('ZoneController', () => { + let application; + + const setup = async (html) => { + document.body.innerHTML = `<main>${html}</main>`; + + application = Application.start(); + application.register('w-zone', ZoneController); + + await Promise.resolve(); + }; + + afterEach(() => { + application?.stop(); + jest.clearAllMocks(); + }); + + describe('activate method', () => { + it('should add active class to the element', async () => { + await setup(` + <div + class="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="hovered" + data-action="dragover->w-zone#activate" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + element.dispatchEvent(new Event('dragover')); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(true); + }); + }); + + describe('deactivate method', () => { + it('should remove active class from the element', async () => { + await setup(` + <div + class="drop-zone hovered" + data-controller="w-zone" + data-w-zone-mode-value="active" + data-w-zone-active-class="hovered" + data-action="dragleave->w-zone#deactivate" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + element.dispatchEvent(new Event('dragleave')); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(false); + }); + + it('should not throw an error if active class is not present', async () => { + await setup(` + <div + class="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="hovered" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + expect(() => element.dispatchEvent(new Event('dragleave'))).not.toThrow(); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(false); + }); + }); + + describe('noop method', () => { + it('should allow for arbitrary stimulus actions via the noop method', async () => { + await setup(` + <div + class="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="hovered" + data-action="drop->w-zone#noop:prevent" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + const dropEvent = new Event('drop', { bubbles: true, cancelable: true }); + element.dispatchEvent(dropEvent); + await jest.runAllTimersAsync(); + expect(dropEvent.defaultPrevented).toBe(true); + }); + }); + + describe('delay value', () => { + it('should delay the mode change by the provided value', async () => { + await setup(` + <div + class="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="active" + data-w-zone-delay-value="100" + data-action="dragover->w-zone#activate dragleave->w-zone#deactivate" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + + element.dispatchEvent(new Event('dragover')); + await Promise.resolve(jest.advanceTimersByTime(50)); + + expect(element.classList.contains('active')).toBe(false); + + await jest.advanceTimersByTime(55); + expect(element.classList.contains('active')).toBe(true); + + // deactivate should take twice as long (100 x 2 = 200ms) + + element.dispatchEvent(new Event('dragleave')); + + await Promise.resolve(jest.advanceTimersByTime(180)); + + expect(element.classList.contains('active')).toBe(true); + + await Promise.resolve(jest.advanceTimersByTime(20)); + expect(element.classList.contains('active')).toBe(false); + }); + }); + + describe('example usage for drag & drop', () => { + it('should handle multiple drag-related events correctly', async () => { + await setup(` + <div + class="drop-zone" + data-controller="w-zone" + data-w-zone-active-class="hovered" + data-action="dragover->w-zone#activate:prevent dragleave->w-zone#deactivate dragend->w-zone#deactivate" + ></div> + `); + + const element = document.querySelector('.drop-zone'); + + // Simulate dragover + const dragoverEvent = new Event('dragover', { + bubbles: true, + cancelable: true, + }); + element.dispatchEvent(dragoverEvent); + expect(dragoverEvent.defaultPrevented).toBe(true); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(true); + + // Simulate dragleave + element.dispatchEvent(new Event('dragleave')); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(false); + + // Simulate dragover again for dragend + element.dispatchEvent(dragoverEvent); + expect(dragoverEvent.defaultPrevented).toBe(true); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(true); + + // Simulate dragend + element.dispatchEvent(new Event('dragend')); + await jest.runAllTimersAsync(); + expect(element.classList.contains('hovered')).toBe(false); + }); + }); +});
null
null
wagtail
12,643
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 602d849422ba..0eef17a620a1 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -29,6 +29,7 @@ Changelog * Fix: Ensure the accessible labels and tooltips reflect the correct private/public status on the live link button within pages after changing the privacy (Ayaan Qadri) * Fix: Fix empty `th` (table heading) elements that are not compliant with accessibility standards (Jai Vignesh J) * Fix: Ensure `MultipleChooserPanel` using images or documents work when nested within an `InlinePanel` when no other choosers are in use within the model (Elhussein Almasri) + * Fix: Ensure `MultipleChooserPanel` works after doing a search in the page chooser modal (Matt Westcott) * Fix: Ensure new `ListBlock` instances get created with unique IDs in the admin client for accessibility and mini-map element references (Srishti Jaiswal) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) diff --git a/client/src/entrypoints/admin/page-chooser-modal.js b/client/src/entrypoints/admin/page-chooser-modal.js index 381bcc3074d2..a7ee3539f9a7 100644 --- a/client/src/entrypoints/admin/page-chooser-modal.js +++ b/client/src/entrypoints/admin/page-chooser-modal.js @@ -69,6 +69,16 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { $(this).data('timer', wait); }); + function updateMultipleChoiceSubmitEnabledState() { + // update the enabled state of the multiple choice submit button depending on whether + // any items have been selected + if ($('[data-multiple-choice-select]:checked', modal.body).length) { + $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); + } else { + $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); + } + } + /* Set up behaviour of choose-page links in the newly-loaded search results, to pass control back to the calling page */ function ajaxifySearchResults() { @@ -95,16 +105,11 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { modal.loadUrl(this.href); return false; }); - } - function updateMultipleChoiceSubmitEnabledState() { - // update the enabled state of the multiple choice submit button depending on whether - // any items have been selected - if ($('[data-multiple-choice-select]:checked', modal.body).length) { - $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); - } else { - $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); - } + updateMultipleChoiceSubmitEnabledState(); + $('[data-multiple-choice-select]', modal.body).on('change', () => { + updateMultipleChoiceSubmitEnabledState(); + }); } function ajaxifyBrowseResults() { diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 57e2b9b9600f..c6aa5b5c00c2 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -41,6 +41,7 @@ depth: 1 * Ensure the accessible labels and tooltips reflect the correct private/public status on the live link button within pages after changing the privacy (Ayaan Qadri) * Fix empty `th` (table heading) elements that are not compliant with accessibility standards (Jai Vignesh J) * Ensure `MultipleChooserPanel` using images or documents work when nested within an `InlinePanel` when no other choosers are in use within the model (Elhussein Almasri) + * Ensure `MultipleChooserPanel` works after doing a search in the page chooser modal (Matt Westcott) * Ensure new `ListBlock` instances get created with unique IDs in the admin client for accessibility and mini-map element references (Srishti Jaiswal) ### Documentation diff --git a/wagtail/admin/templates/wagtailadmin/chooser/browse.html b/wagtail/admin/templates/wagtailadmin/chooser/browse.html index e421226ecf81..66caccc3daf1 100644 --- a/wagtail/admin/templates/wagtailadmin/chooser/browse.html +++ b/wagtail/admin/templates/wagtailadmin/chooser/browse.html @@ -5,7 +5,8 @@ {% trans "Choose a page" as choose_str %} {% endif %} -{% include "wagtailadmin/shared/header.html" with title=choose_str subtitle=page_type_names|join:", " search_url="wagtailadmin_choose_page_search" query_parameters="page_type="|add:page_type_string icon="doc-empty-inverse" search_disable_async=True %} +{% querystring as search_query_params %} +{% include "wagtailadmin/shared/header.html" with title=choose_str subtitle=page_type_names|join:", " search_url="wagtailadmin_choose_page_search" query_parameters=search_query_params icon="doc-empty-inverse" search_disable_async=True %} <div class="nice-padding"> {% include 'wagtailadmin/chooser/_link_types.html' with current='internal' %} diff --git a/wagtail/admin/templates/wagtailadmin/chooser/tables/parent_page_cell.html b/wagtail/admin/templates/wagtailadmin/chooser/tables/parent_page_cell.html index c8aa24d937f6..ad754ae243c6 100644 --- a/wagtail/admin/templates/wagtailadmin/chooser/tables/parent_page_cell.html +++ b/wagtail/admin/templates/wagtailadmin/chooser/tables/parent_page_cell.html @@ -1,7 +1,7 @@ {% load wagtailadmin_tags %} <td {% if column.classname %}class="{{ column.classname }}"{% endif %}> {% if value %} - <a href="{% url 'wagtailadmin_choose_page_child' value.id %}" class="navigate-parent">{{ value.get_admin_display_title }}</a> + <a href="{% url 'wagtailadmin_choose_page_child' value.id %}{% querystring p=None q=None %}" class="navigate-parent">{{ value.get_admin_display_title }}</a> {% if show_locale_labels %}{% status value.locale.get_display_name classname="w-status--label" %}{% endif %} {% endif %} </td> diff --git a/wagtail/admin/templates/wagtailadmin/shared/header.html b/wagtail/admin/templates/wagtailadmin/shared/header.html index 8f2400656872..9095b3757a2d 100644 --- a/wagtail/admin/templates/wagtailadmin/shared/header.html +++ b/wagtail/admin/templates/wagtailadmin/shared/header.html @@ -11,7 +11,7 @@ - `search_results_url` - URL to be used for async requests to search results, if not provided, the form's action URL will be used - `search_target` - A selector string to be used as the target for the search results to be swapped into. Defaults to '#listing-results' - `search_disable_async` - If True, the default header async search functionality will not be used - - `query_parameters` - a query string (without the '?') to be placed after the search URL + - `query_parameters` - a query string (with or without the '?') to be placed after the search URL - `icon` - name of an icon to place against the title - `merged` - if true, add the classname 'w-header--merged' - `action_url` - if present, display an 'action' button. This is the URL to be used as the link URL for the button @@ -42,7 +42,7 @@ <h1 class="w-header__title" id="header-title"> {% if search_url %} <form class="col search-form" - action="{% url search_url %}{% if query_parameters %}?{{ query_parameters }}{% endif %}" + action="{% url search_url %}{% if query_parameters %}{% if query_parameters.0 != '?' %}?{% endif %}{{ query_parameters }}{% endif %}" method="get" novalidate role="search" diff --git a/wagtail/admin/views/chooser.py b/wagtail/admin/views/chooser.py index 8ec9dde8b967..66c5e63e7951 100644 --- a/wagtail/admin/views/chooser.py +++ b/wagtail/admin/views/chooser.py @@ -408,7 +408,11 @@ class SearchView(View): @property def columns(self): cols = [ - PageTitleColumn("title", label=_("Title")), + PageTitleColumn( + "title", + label=_("Title"), + is_multiple_choice=self.is_multiple_choice, + ), ParentPageColumn("parent", label=_("Parent")), DateColumn( "updated",
c2676af857a41440e05e03038d85a540dcca3ce2
Enable/disable the submit button based on checkbox selections and attach change event handlers to checkboxes in search results.
The following is the text of a github issue and related comments for this repository: Uncaught TypeError in page-editor.js - MultipleChooserPanel <!-- Found a bug? Please fill out the sections below. 👍 --> ### Issue Summary I have selection of authors for a book in my site ![Screenshot 2024-05-14 at 15 51 11](https://github.com/wagtail/wagtail/assets/10074977/e0883697-3622-43c9-8f18-17cc1e15384e) And I can select whichever one without issue! The problem comes when I try to filter by author name, the filtering occurs without any problems but I cannot select any of the authors from the output. The result is correct, I get the color change on hover meaning I can click on it: ![Screenshot 2024-05-14 at 15 54 27](https://github.com/wagtail/wagtail/assets/10074977/27938ae7-caea-4fb3-aef0-7c72c3f8f0e1) But when I do I get this in the console making reference to `page-editor.js`: ```Uncaught TypeError: e.forEach is not a function at chooserWidgetFactory.openModal.multiple (page-editor.js?v=0055a0ab:1:5607) at Object.pageChosen (vendor.js?v=0055a0ab:2:260739) at o.respond (modal-workflow.js?v=0055a0ab:1:2056) at HTMLAnchorElement.<anonymous> (page-chooser-modal.js?v=0055a0ab:1:758) at HTMLAnchorElement.dispatch (jquery-3.6.0.min.js?v=0055a0ab:2:43003) at v.handle (jquery-3.6.0.min.js?v=055a0ab:2:40998) ``` ### Steps to Reproduce Assuming you have a working Wagtail app running: 1. Go to edit any page with a MultipleChooserPanel (classic example of a Blog Post with an Author) 2. Filter by the author name 3. See you cannot select any of the given results after the filtering is done. - I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: no ### Technical details - Python version: `3.9.15` - Django version: `4.2.11` - Wagtail version: `5.2.3` - Browser version: `Chrome 124` ### Working on this In the [original conversation](https://wagtailcms.slack.com/archives/C81FGJR2S/p1715695098743519) on the Slack support channel @lb- mentioned that his guess was that the chooser JS is not being reinstated after the filtering occurs. The checkboxes are missing from the second screenshot, which probably means that the URL parameter that enables multiple choice has not been preserved when loading the filtered results - it then ends up returning a single result (rather than the expected array of results) to the calling page, which fails as the calling page tries to loop over the results. FYI, in case it helps, the behaviour is correct when you try to change an existing author. If you have a selected item in your MultipleChooserPanel and want to change it, using the menu option "Choose another page" you get the pop-up/modal and filtering works there without issue. I still don't get the checkboxes but I can click the results and the value changes correctly. Several bugs to fix: - The search bar's action URL needs to preserve all URL parameters from the initial opening of the modal, not just page_types - this includes multiple (so that we don't drop back to single-select mode after a search) but also others that influence the results, such as user_perms (without this, the parent page chooser in the "move page" view will let you choose pages in search results that are greyed out while in browse mode) as well as allow_external_links and friends (which are not used directly by the search results view, but need to be passed on through the parent page link so that we don't lose the top navigation when we return to browse mode). - ajaxifySearchResults was not attaching the event handler to the checkboxes for enabling/disabling the "confirm selection" button, so it was never being enabled - The parent page link in the search results was not preserving any URL params - it needs to preserve all except the search query q and page number p. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/client/src/entrypoints/admin/page-chooser-modal.js b/client/src/entrypoints/admin/page-chooser-modal.js index 381bcc3074d2..a7ee3539f9a7 100644 --- a/client/src/entrypoints/admin/page-chooser-modal.js +++ b/client/src/entrypoints/admin/page-chooser-modal.js @@ -69,6 +69,16 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { $(this).data('timer', wait); }); + function updateMultipleChoiceSubmitEnabledState() { + // update the enabled state of the multiple choice submit button depending on whether + // any items have been selected + if ($('[data-multiple-choice-select]:checked', modal.body).length) { + $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); + } else { + $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); + } + } + /* Set up behaviour of choose-page links in the newly-loaded search results, to pass control back to the calling page */ function ajaxifySearchResults() { @@ -95,16 +105,11 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { modal.loadUrl(this.href); return false; }); - } - function updateMultipleChoiceSubmitEnabledState() { - // update the enabled state of the multiple choice submit button depending on whether - // any items have been selected - if ($('[data-multiple-choice-select]:checked', modal.body).length) { - $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); - } else { - $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); - } + updateMultipleChoiceSubmitEnabledState(); + $('[data-multiple-choice-select]', modal.body).on('change', () => { + updateMultipleChoiceSubmitEnabledState(); + }); } function ajaxifyBrowseResults() {
diff --git a/wagtail/admin/tests/test_page_chooser.py b/wagtail/admin/tests/test_page_chooser.py index d054f8b22723..5ec5cfbdba00 100644 --- a/wagtail/admin/tests/test_page_chooser.py +++ b/wagtail/admin/tests/test_page_chooser.py @@ -65,12 +65,20 @@ def test_multiple_chooser_view(self): checkbox_value = str(self.child_page.id) decoded_content = response.content.decode() + response_json = json.loads(decoded_content) + self.assertEqual(response_json["step"], "browse") + response_html = response_json["html"] - self.assertIn(f'value=\\"{checkbox_value}\\"', decoded_content) + self.assertIn(f'value="{checkbox_value}"', response_html) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html") + soup = self.get_soup(response_html) + search_url = soup.find("form", role="search")["action"] + search_query_params = parse_qs(urlsplit(search_url).query) + self.assertEqual(search_query_params["multiple"], ["1"]) + @override_settings(USE_THOUSAND_SEPARATOR=False) def test_multiple_chooser_view_without_thousand_separator(self): self.page = Page.objects.get(id=1) @@ -363,12 +371,22 @@ def get(self, params=None): return self.client.get(reverse("wagtailadmin_choose_page_search"), params or {}) def test_simple(self): - response = self.get({"q": "foobarbaz"}) + response = self.get({"q": "foobarbaz", "allow_external_link": "true"}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html") self.assertContains(response, "There is 1 match") self.assertContains(response, "foobarbaz") + # parent page link should preserve the allow_external_link parameter + expected_url = ( + reverse("wagtailadmin_choose_page_child", args=[self.root_page.id]) + + "?allow_external_link=true" + ) + self.assertContains( + response, + f'<a href="{expected_url}" class="navigate-parent">{self.root_page.title}</a>', + ) + def test_partial_match(self): response = self.get({"q": "fooba"}) self.assertEqual(response.status_code, 200)
diff --git a/client/src/entrypoints/admin/page-chooser-modal.js b/client/src/entrypoints/admin/page-chooser-modal.js index 381bcc3074d2..a7ee3539f9a7 100644 --- a/client/src/entrypoints/admin/page-chooser-modal.js +++ b/client/src/entrypoints/admin/page-chooser-modal.js @@ -69,6 +69,16 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { function updateMultipleChoiceSubmitEnabledState( @@ -95,16 +105,11 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { u $
diff --git a/client/src/entrypoints/admin/page-chooser-modal.js b/client/src/entrypoints/admin/page-chooser-modal.js index 381bcc3074d2..a7ee3539f9a7 100644 --- a/client/src/entrypoints/admin/page-chooser-modal.js +++ b/client/src/entrypoints/admin/page-chooser-modal.js @@ -69,6 +69,16 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { $(this).data('timer', wait); }); + function updateMultipleChoiceSubmitEnabledState() { + // update the enabled state of the multiple choice submit button depending on whether + // any items have been selected + if ($('[data-multiple-choice-select]:checked', modal.body).length) { + $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); + } else { + $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); + } + } + /* Set up behaviour of choose-page links in the newly-loaded search results, to pass control back to the calling page */ function ajaxifySearchResults() { @@ -95,16 +105,11 @@ const PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { modal.loadUrl(this.href); return false; }); - } - function updateMultipleChoiceSubmitEnabledState() { - // update the enabled state of the multiple choice submit button depending on whether - // any items have been selected - if ($('[data-multiple-choice-select]:checked', modal.body).length) { - $('[data-multiple-choice-submit]', modal.body).removeAttr('disabled'); - } else { - $('[data-multiple-choice-submit]', modal.body).attr('disabled', true); - } + updateMultipleChoiceSubmitEnabledState(); + $('[data-multiple-choice-select]', modal.body).on('change', () => { + updateMultipleChoiceSubmitEnabledState(); + }); } function ajaxifyBrowseResults() {
wagtail
12,619
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index cfeea825126a..4411028ac2b8 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -60,6 +60,7 @@ Changelog * Maintenance: Migrate jQuery class toggling & drag/drop event handling within the multiple upload views to the Stimulus ZoneController usage (Ayaan Qadri) * Maintenance: Test project template for warnings when run against Django pre-release versions (Sage Abdullah) * Maintenance: Refactor redirects create/delete views to use generic views (Sage Abdullah) + * Maintenance: Add JSDoc description, adopt linting recommendations, and add more unit tests for `ModalWorkflow` (LB (Ben) Johnston) 6.3.2 (xx.xx.xxxx) - IN DEVELOPMENT diff --git a/client/src/entrypoints/admin/modal-workflow.js b/client/src/entrypoints/admin/modal-workflow.js index 2955f763eee3..54737ed19369 100644 --- a/client/src/entrypoints/admin/modal-workflow.js +++ b/client/src/entrypoints/admin/modal-workflow.js @@ -91,15 +91,15 @@ function ModalWorkflow(opts) { }; self.ajaxifyForm = function ajaxifyForm(formSelector) { - $(formSelector).each(() => { + $(formSelector).each(function ajaxifyFormInner() { const action = this.action; if (this.method.toLowerCase() === 'get') { - $(this).on('submit', () => { + $(this).on('submit', function handleSubmit() { self.loadUrl(action, $(this).serialize()); return false; }); } else { - $(this).on('submit', () => { + $(this).on('submit', function handleSubmit() { self.postForm(action, $(this).serialize()); return false; }); diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 5dff2827c18f..a77da22022e3 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -79,6 +79,7 @@ depth: 1 * Migrate jQuery class toggling & drag/drop event handling within the multiple upload views to the Stimulus ZoneController usage (Ayaan Qadri) * Test project template for warnings when run against Django pre-release versions (Sage Abdullah) * Refactor redirects create/delete views to use generic views (Sage Abdullah) + * Add JSDoc description, adopt linting recommendations, and add more unit tests for `ModalWorkflow` (LB (Ben) Johnston) ## Upgrade considerations - changes affecting all projects
9cacfe0dc2b30053f4bd028236316e7248a1074c
Replace arrow functions with regular functions to maintain the correct `this` binding in form submissions.
The following is the text of a github issue and related comments for this repository: Page choosers no longer working on `main` <!-- Found a bug? Please fill out the sections below. 👍 --> ### Issue Summary The page chooser modal will not respond to any clicks when choosing a page, and an error is thrown in the console: `Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase') at HTMLFormElement.eval (modal-workflow.js:81:1) at Function.each (jquery-3.6.0.min.js?v=bd94a3b0:2:3003) at S.fn.init.each (jquery-3.6.0.min.js?v=bd94a3b0:2:1481) at Object.ajaxifyForm (modal-workflow.js:79:1) at Object.browse (page-chooser-modal.js:18:1) at Object.loadBody (modal-workflow.js:113:1) at Object.loadResponseText [as success] (modal-workflow.js:97:1) at c (jquery-3.6.0.min.js?v=bd94a3b0:2:28327) at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js?v=bd94a3b0:2:29072) at l (jquery-3.6.0.min.js?v=bd94a3b0:2:79901) ### Steps to Reproduce 1. Spin up bakerydemo 2. Edit the "Welcome to the Wagtail bakery!" page 3. On the "Hero CTA link", click on the ... button > Choose another page 4. Try to choose any other page 5. Observe that the modal stays open and the error is thrown in the console Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead? The modal should be closed and the newly chosen page should replace the previously chosen one. - I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes on bakerydemo ### Working on this This is a confirmed regression in #12380, specifically the changes in `ajaxifyForm` where the anonymous function is replaced with an arrow function, which results in a different object being bound to `this`. There are other similar changes in the PR, so there might be other choosers/modals broken as a result. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/client/src/entrypoints/admin/modal-workflow.js b/client/src/entrypoints/admin/modal-workflow.js index 2955f763eee3..54737ed19369 100644 --- a/client/src/entrypoints/admin/modal-workflow.js +++ b/client/src/entrypoints/admin/modal-workflow.js @@ -91,15 +91,15 @@ function ModalWorkflow(opts) { }; self.ajaxifyForm = function ajaxifyForm(formSelector) { - $(formSelector).each(() => { + $(formSelector).each(function ajaxifyFormInner() { const action = this.action; if (this.method.toLowerCase() === 'get') { - $(this).on('submit', () => { + $(this).on('submit', function handleSubmit() { self.loadUrl(action, $(this).serialize()); return false; }); } else { - $(this).on('submit', () => { + $(this).on('submit', function handleSubmit() { self.postForm(action, $(this).serialize()); return false; });
diff --git a/client/src/entrypoints/admin/__snapshots__/modal-workflow.test.js.snap b/client/src/entrypoints/admin/__snapshots__/modal-workflow.test.js.snap index a5f1675e428f..42497f9a15d6 100644 --- a/client/src/entrypoints/admin/__snapshots__/modal-workflow.test.js.snap +++ b/client/src/entrypoints/admin/__snapshots__/modal-workflow.test.js.snap @@ -45,6 +45,18 @@ HTMLCollection [ > path/to/endpoint </div> + + + <form + action="/path/to/form/submit" + id="form" + method="post" + > + <input + name="key" + value="value" + /> + </form> </div> diff --git a/client/src/entrypoints/admin/modal-workflow.test.js b/client/src/entrypoints/admin/modal-workflow.test.js index 0a5235f50362..bcfa56bcc07e 100644 --- a/client/src/entrypoints/admin/modal-workflow.test.js +++ b/client/src/entrypoints/admin/modal-workflow.test.js @@ -8,13 +8,29 @@ import './modal-workflow'; $.get = jest.fn().mockImplementation((url, data, cb) => { cb( - JSON.stringify({ html: `<div id="url">${url}</div>`, data, step: 'start' }), + JSON.stringify({ + data, + html: `<div id="url">${url}</div> + <form id="form" method="post" action="/path/to/form/submit"><input name="key" value="value"></input></form>`, + step: 'start', + }), + ); + return { fail: jest.fn() }; +}); + +$.post = jest.fn((url, data, cb) => { + cb( + JSON.stringify({ + html: '<div id="response">response</div>', + }), ); return { fail: jest.fn() }; }); describe('modal-workflow', () => { beforeEach(() => { + jest.clearAllMocks(); + document.body.innerHTML = '<div id="content"><button data-chooser-action-choose id="trigger">Open</button></div>'; }); @@ -102,6 +118,31 @@ describe('modal-workflow', () => { expect(triggerButton.disabled).toBe(false); }); + it('should expose a `ajaxifyForm` method that allows forms to be submitted async', () => { + expect($.post).toHaveBeenCalledTimes(0); + expect(document.querySelectorAll('.modal-body #response')).toHaveLength(0); + + const modalWorkflow = window.ModalWorkflow({ url: 'path/to/endpoint' }); + + modalWorkflow.ajaxifyForm('#form'); + + const event = new Event('submit'); + event.preventDefault = jest.fn(); + document.getElementById('form').dispatchEvent(event); + + expect(event.preventDefault).toHaveBeenCalled(); + + expect($.post).toHaveBeenCalledTimes(1); + expect($.post).toHaveBeenCalledWith( + 'http://localhost/path/to/form/submit', + 'key=value', + expect.any(Function), + 'text', + ); + + expect(document.querySelectorAll('.modal-body #response')).toHaveLength(1); + }); + it('should handle onload and URL param options', () => { const onload = { start: jest.fn() }; const urlParams = { page: 23 }; @@ -125,12 +166,15 @@ describe('modal-workflow', () => { expect(modalWorkflow).toBeInstanceOf(Object); - // important: see mock implementation above, returning a response with injected data to validate behaviour + // important: see mock implementation above, returning a response with injected data to validate behavior const response = { data: urlParams, - html: '<div id="url">path/to/endpoint</div>', + html: expect.stringContaining('<div id="url">path/to/endpoint</div>'), step: 'start', }; - expect(onload.start).toHaveBeenCalledWith(modalWorkflow, response); + expect(onload.start).toHaveBeenCalledWith( + modalWorkflow, + expect.objectContaining(response), + ); }); });
null
null
wagtail
12,666
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 0eef17a620a1..98757878477c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -87,6 +87,7 @@ Changelog * Maintenance: Use the Stimulus `ZoneController` (`w-zone`) to remove ad-hoc jQuery for the privacy switch when toggling visibility of private/public elements (Ayaan Qadri) * Maintenance: Remove unused `is_active` & `active_menu_items` from `wagtail.admin.menu.MenuItem` (Srishti Jaiswal) * Maintenance: Only call `openpyxl` at runtime to improve performance for projects that do not use `ReportView`, `SpreadsheetExportMixin` and `wagtail.contrib.redirects` (Sébastien Corbin) + * Maintenance: Adopt the update value `mp` instead of `mm` for 'mystery person' as the default Gravatar if no avatar found (Harsh Dange) 6.3.2 (xx.xx.xxxx) - IN DEVELOPMENT diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1fbd97cac3be..3a93220731b3 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -858,6 +858,7 @@ * Noah van der Meer * Strapchay * Alex Fulcher +* Harsh Dange ## Translators diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index c6aa5b5c00c2..b043aab52ddb 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -105,6 +105,7 @@ depth: 1 * Use the Stimulus `ZoneController` (`w-zone`) to remove ad-hoc jQuery for the privacy switch when toggling visibility of private/public elements (Ayaan Qadri) * Remove unused `is_active` & `active_menu_items` from `wagtail.admin.menu.MenuItem` (Srishti Jaiswal) * Only call `openpyxl` at runtime to improve performance for projects that do not use `ReportView`, `SpreadsheetExportMixin` and `wagtail.contrib.redirects` (Sébastien Corbin) + * Adopt the update value `mp` instead of `mm` for 'mystery person' as the default Gravatar if no avatar found (Harsh Dange) ## Upgrade considerations - changes affecting all projects diff --git a/wagtail/users/utils.py b/wagtail/users/utils.py index ef3f0e6bb9c1..b3eee7970d07 100644 --- a/wagtail/users/utils.py +++ b/wagtail/users/utils.py @@ -26,7 +26,7 @@ def user_can_delete_user(current_user, user_to_delete): def get_gravatar_url(email, size=50): - default = "mm" + default = "mp" size = ( int(size) * 2 ) # requested at retina size by default and scaled down at point of use with css
23275a4cef4d36bb311abe315eb9ddfc43868e8b
Update default profile image to "mp".
The following is the text of a github issue and related comments for this repository: Default URL param value for Gravatar URL have been deprecated (`mm` -> `mp`) ### Issue Summary We currently pass in `mm` to the `d` (default) param, this is used to determine what avatar will show if there's no matching avatar. However, the latest documentation advises that this should be `mp` (mystery person) instead. https://github.com/wagtail/wagtail/blob/c2676af857a41440e05e03038d85a540dcca3ce2/wagtail/users/utils.py#L28-L29 https://github.com/wagtail/wagtail/blob/c2676af857a41440e05e03038d85a540dcca3ce2/wagtail/users/utils.py#L45 https://docs.gravatar.com/api/avatars/images/#default-image ### Describe the solution you'd like Update the param value from `mm` to `mp` and ensure any unit tests are updated. This way, if the support for this legacy value gets dropped, it will not be a breaking change for Wagtail users. ### Describe alternatives you've considered It might be nice to have a better approach to this by allowing the param to be passed into the function / overridden somehow. Best to discuss that in a different issue though - see https://github.com/wagtail/wagtail/issues/12659 ### Additional context Two PRs have attempted this (and other changes), see the feedback and the PRs for reference. - #11077 - #11800 ### Working on this - Anyone can contribute to this, be sure you understand how to reproduce the avatar scenario. - It might be good to tackle this small change before tackling the other related issues. - View our [contributing guidelines](https://docs.wagtail.org/en/latest/contributing/index.html), add a comment to the issue once you’re ready to start. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/users/utils.py b/wagtail/users/utils.py index ef3f0e6bb9c1..b3eee7970d07 100644 --- a/wagtail/users/utils.py +++ b/wagtail/users/utils.py @@ -26,7 +26,7 @@ def user_can_delete_user(current_user, user_to_delete): def get_gravatar_url(email, size=50): - default = "mm" + default = "mp" size = ( int(size) * 2 ) # requested at retina size by default and scaled down at point of use with css
diff --git a/wagtail/admin/tests/ui/test_sidebar.py b/wagtail/admin/tests/ui/test_sidebar.py index e5c21bc7f049..f2e160144651 100644 --- a/wagtail/admin/tests/ui/test_sidebar.py +++ b/wagtail/admin/tests/ui/test_sidebar.py @@ -283,7 +283,7 @@ def test_adapt(self): ], { "name": user.first_name or user.get_username(), - "avatarUrl": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=100&d=mm", + "avatarUrl": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=100&d=mp", }, ], },
null
null
wagtail
12,605
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 4a5ad0704f70..20898fa5ff89 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -23,6 +23,7 @@ Changelog * Fix: Use correct connections on multi-database setups in database search backends (Jake Howard) * Fix: Ensure Cloudfront cache invalidation is called with a list, for compatibility with current botocore versions (Jake Howard) * Fix: Show the correct privacy status in the sidebar when creating a new page (Joel William) + * Fix: Prevent generic model edit view from unquoting non-integer primary keys multiple times (Matt Westcott) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) * Docs: Move the tags documentation to standalone advanced topic, instead of being inside the reference/pages section (Srishti Jaiswal) diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 7c54a9ecd7dc..d6c931e5697c 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -36,6 +36,7 @@ depth: 1 * Use correct connections on multi-database setups in database search backends (Jake Howard) * Ensure Cloudfront cache invalidation is called with a list, for compatibility with current botocore versions (Jake Howard) * Show the correct privacy status in the sidebar when creating a new page (Joel William) + * Prevent generic model edit view from unquoting non-integer primary keys multiple times (Matt Westcott) ### Documentation diff --git a/wagtail/admin/views/generic/models.py b/wagtail/admin/views/generic/models.py index 636f7d13ef44..eac1265bb50a 100644 --- a/wagtail/admin/views/generic/models.py +++ b/wagtail/admin/views/generic/models.py @@ -677,6 +677,16 @@ def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.action = self.get_action(request) + @cached_property + def object_pk(self): + # Must be a cached_property to prevent this from being re-run on the unquoted + # pk written back by get_object, which would result in it being unquoted again. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + return unquote(str(quoted_pk)) + def get_action(self, request): for action in self.get_available_actions(): if request.POST.get(f"action-{action}"): @@ -687,9 +697,9 @@ def get_available_actions(self): return self.actions def get_object(self, queryset=None): - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + self.kwargs[self.pk_url_kwarg] = self.object_pk return super().get_object(queryset) def get_page_subtitle(self): @@ -947,9 +957,15 @@ def get_object(self, queryset=None): # If the object has already been loaded, return it to avoid another query if getattr(self, "object", None): return self.object - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + self.kwargs[self.pk_url_kwarg] = unquote(str(quoted_pk)) + return super().get_object(queryset) def get_usage(self):
ffe294bc7bb3fe49674a4b6eb87fe223b3348e01
Cache the unquoted primary key to prevent double unquoting, and update both `get_object` methods to properly use the cached value.
The following is the text of a github issue and related comments for this repository: Snippets EditView unexpected double unquote ### Issue Summary In case of EditView code snippets (I think this happens with all views as well), the get_object() method in wagtail/wagtail/admin/views/generic/models.py/EditView is called multiple times. This creates a problem when the object pk has quoted characters. ### Steps to Reproduce 1 Add object with pk web_407269_1 2. Add snippets view for this model 3. Try to edit that object results in 404 error I haven't confirmed that this issue can be reproduced as described on a fresh Wagtail project ### Technical details Seems that when try to unquote it works in the first query before calling hooks but it fail on the second call of get_object() https://github.com/wagtail/wagtail/blob/main/wagtail/admin/views/generic/models.py#L692 web_5F407269_5F1 ---(first unquote)---> web_407269_1 ---(second unquote)---> web_@7269_1 This result on the second query unable to find the object I can confirm this on the current main branch, using a test project created with wagtail start and home/models.py edited to: ```python from django.db import models from wagtail.admin.panels import FieldPanel from wagtail.models import Page from wagtail.snippets.models import register_snippet class HomePage(Page): pass @register_snippet class Thing(models.Model): id = models.CharField(primary_key=True, max_length=32) name = models.CharField(max_length=255) panels = [ FieldPanel("name"), ] ``` From the ./manage.py shell prompt: ``` >>> from home.models import Thing >>> Thing.objects.create(pk="abc", name="normal thing") <Thing: Thing object (abc)> >>> Thing.objects.create(pk="web_407269_1", name="strange thing") <Thing: Thing object (web_407269_1)> ``` Within the Wagtail admin, under Snippets -> Things, the item with pk "abc" is editable but the item with pk "web_407269_1" yields a 404 error. Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/admin/views/generic/models.py b/wagtail/admin/views/generic/models.py index 636f7d13ef44..eac1265bb50a 100644 --- a/wagtail/admin/views/generic/models.py +++ b/wagtail/admin/views/generic/models.py @@ -677,6 +677,16 @@ def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.action = self.get_action(request) + @cached_property + def object_pk(self): + # Must be a cached_property to prevent this from being re-run on the unquoted + # pk written back by get_object, which would result in it being unquoted again. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + return unquote(str(quoted_pk)) + def get_action(self, request): for action in self.get_available_actions(): if request.POST.get(f"action-{action}"): @@ -687,9 +697,9 @@ def get_available_actions(self): return self.actions def get_object(self, queryset=None): - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + self.kwargs[self.pk_url_kwarg] = self.object_pk return super().get_object(queryset) def get_page_subtitle(self): @@ -947,9 +957,15 @@ def get_object(self, queryset=None): # If the object has already been loaded, return it to avoid another query if getattr(self, "object", None): return self.object - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + self.kwargs[self.pk_url_kwarg] = unquote(str(quoted_pk)) + return super().get_object(queryset) def get_usage(self):
diff --git a/wagtail/admin/tests/test_views_generic.py b/wagtail/admin/tests/test_views_generic.py index 5f3a425ac82a..9dc605f17153 100644 --- a/wagtail/admin/tests/test_views_generic.py +++ b/wagtail/admin/tests/test_views_generic.py @@ -15,7 +15,7 @@ def test_non_integer_primary_key(self): response = self.get() self.assertEqual(response.status_code, 200) response_object_count = response.context_data["object_list"].count() - self.assertEqual(response_object_count, 3) + self.assertEqual(response_object_count, 4) self.assertContains(response, "first modelwithstringtypeprimarykey model") self.assertContains(response, "second modelwithstringtypeprimarykey model") soup = self.get_soup(response.content) @@ -34,7 +34,7 @@ def test_non_integer_primary_key(self): response = self.get() self.assertEqual(response.status_code, 200) response_object_count = response.context_data["object_list"].count() - self.assertEqual(response_object_count, 3) + self.assertEqual(response_object_count, 4) class TestGenericEditView(WagtailTestUtils, TestCase): @@ -58,19 +58,29 @@ def test_non_url_safe_primary_key(self): response, "non-url-safe pk modelwithstringtypeprimarykey model" ) - def test_using_quote_in_edit_url(self): - object_pk = 'string-pk-:#?;@&=+$,"[]<>%' + def test_unquote_sensitive_primary_key(self): + object_pk = "web_407269_1" response = self.get(quote(object_pk)) - edit_url = response.context_data["action_url"] - edit_url_pk = edit_url.split("/")[-2] - self.assertEqual(edit_url_pk, quote(object_pk)) + self.assertEqual(response.status_code, 200) + self.assertContains( + response, "unquote-sensitive modelwithstringtypeprimarykey model" + ) + + def test_using_quote_in_edit_url(self): + for object_pk in ('string-pk-:#?;@&=+$,"[]<>%', "web_407269_1"): + with self.subTest(object_pk=object_pk): + response = self.get(quote(object_pk)) + edit_url = response.context_data["action_url"] + edit_url_pk = edit_url.split("/")[-2] + self.assertEqual(edit_url_pk, quote(object_pk)) def test_using_quote_in_delete_url(self): - object_pk = 'string-pk-:#?;@&=+$,"[]<>%' - response = self.get(quote(object_pk)) - delete_url = response.context_data["delete_url"] - delete_url_pk = delete_url.split("/")[-2] - self.assertEqual(delete_url_pk, quote(object_pk)) + for object_pk in ('string-pk-:#?;@&=+$,"[]<>%', "web_407269_1"): + with self.subTest(object_pk=object_pk): + response = self.get(quote(object_pk)) + delete_url = response.context_data["delete_url"] + delete_url_pk = delete_url.split("/")[-2] + self.assertEqual(delete_url_pk, quote(object_pk)) class TestGenericDeleteView(WagtailTestUtils, TestCase): @@ -89,3 +99,8 @@ def test_with_non_url_safe_primary_key(self): object_pk = 'string-pk-:#?;@&=+$,"[]<>%' response = self.get(quote(object_pk)) self.assertEqual(response.status_code, 200) + + def test_with_unquote_sensitive_primary_key(self): + object_pk = "web_407269_1" + response = self.get(quote(object_pk)) + self.assertEqual(response.status_code, 200) diff --git a/wagtail/snippets/tests/test_snippets.py b/wagtail/snippets/tests/test_snippets.py index c08a5af8c745..6bd8a9506e07 100644 --- a/wagtail/snippets/tests/test_snippets.py +++ b/wagtail/snippets/tests/test_snippets.py @@ -5622,6 +5622,9 @@ def setUp(self): self.snippet_a = StandardSnippetWithCustomPrimaryKey.objects.create( snippet_id="snippet/01", text="Hello" ) + self.snippet_b = StandardSnippetWithCustomPrimaryKey.objects.create( + snippet_id="abc_407269_1", text="Goodbye" + ) def get(self, snippet, params={}): args = [quote(snippet.pk)] @@ -5644,9 +5647,11 @@ def create(self, snippet, post_data={}, model=Advert): ) def test_show_edit_view(self): - response = self.get(self.snippet_a) - self.assertEqual(response.status_code, 200) - self.assertTemplateUsed(response, "wagtailsnippets/snippets/edit.html") + for snippet in [self.snippet_a, self.snippet_b]: + with self.subTest(snippet=snippet): + response = self.get(snippet) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed(response, "wagtailsnippets/snippets/edit.html") def test_edit_invalid(self): response = self.post(self.snippet_a, post_data={"foo": "bar"}) @@ -5669,8 +5674,10 @@ def test_edit(self): ) snippets = StandardSnippetWithCustomPrimaryKey.objects.all() - self.assertEqual(snippets.count(), 2) - self.assertEqual(snippets.last().snippet_id, "snippet_id_edited") + self.assertEqual(snippets.count(), 3) + self.assertEqual( + snippets.order_by("snippet_id").last().snippet_id, "snippet_id_edited" + ) def test_create(self): response = self.create( @@ -5685,40 +5692,48 @@ def test_create(self): ) snippets = StandardSnippetWithCustomPrimaryKey.objects.all() - self.assertEqual(snippets.count(), 2) - self.assertEqual(snippets.last().text, "test snippet") + self.assertEqual(snippets.count(), 3) + self.assertEqual(snippets.order_by("snippet_id").last().text, "test snippet") def test_get_delete(self): - response = self.client.get( - reverse( - "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:delete", - args=[quote(self.snippet_a.pk)], - ) - ) - self.assertEqual(response.status_code, 200) - self.assertTemplateUsed(response, "wagtailadmin/generic/confirm_delete.html") + for snippet in [self.snippet_a, self.snippet_b]: + with self.subTest(snippet=snippet): + response = self.client.get( + reverse( + "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:delete", + args=[quote(snippet.pk)], + ) + ) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed( + response, "wagtailadmin/generic/confirm_delete.html" + ) def test_usage_link(self): - response = self.client.get( - reverse( - "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:delete", - args=[quote(self.snippet_a.pk)], - ) - ) - self.assertEqual(response.status_code, 200) - self.assertTemplateUsed(response, "wagtailadmin/generic/confirm_delete.html") - self.assertContains( - response, - "This standard snippet with custom primary key is referenced 0 times", - ) - self.assertContains( - response, - reverse( - "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:usage", - args=[quote(self.snippet_a.pk)], - ) - + "?describe_on_delete=1", - ) + for snippet in [self.snippet_a, self.snippet_b]: + with self.subTest(snippet=snippet): + response = self.client.get( + reverse( + "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:delete", + args=[quote(snippet.pk)], + ) + ) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed( + response, "wagtailadmin/generic/confirm_delete.html" + ) + self.assertContains( + response, + "This standard snippet with custom primary key is referenced 0 times", + ) + self.assertContains( + response, + reverse( + "wagtailsnippets_snippetstests_standardsnippetwithcustomprimarykey:usage", + args=[quote(snippet.pk)], + ) + + "?describe_on_delete=1", + ) def test_redirect_to_edit(self): with self.assertWarnsRegex( diff --git a/wagtail/test/testapp/fixtures/test.json b/wagtail/test/testapp/fixtures/test.json index 756c3930e9c1..d6fd9e9996f9 100644 --- a/wagtail/test/testapp/fixtures/test.json +++ b/wagtail/test/testapp/fixtures/test.json @@ -1027,5 +1027,12 @@ "fields": { "content": "non-url-safe pk modelwithstringtypeprimarykey model" } + }, + { + "pk": "web_407269_1", + "model": "tests.modelwithstringtypeprimarykey", + "fields": { + "content": "unquote-sensitive modelwithstringtypeprimarykey model" + } } ]
diff --git a/wagtail/admin/views/generic/models.py b/wagtail/admin/views/generic/models.py index 636f7d13ef44..eac1265bb50a 100644 --- a/wagtail/admin/views/generic/models.py +++ b/wagtail/admin/views/generic/models.py @@ -677,6 +677,16 @@ def setup(self, request, *args, **kwargs): @cached_property def object_pk( @@ -687,9 +697,9 @@ def get_available_actions(self): # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, # so we need to write it back there. self.kwargs[self.pk_url_kwarg] = @@ -947,9 +957,15 @@ def get_object(self, queryset=None): # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, # so we need to write it back there. try: quoted_pk = self.kwargs[self.pk_url_kwarg] =
diff --git a/wagtail/admin/views/generic/models.py b/wagtail/admin/views/generic/models.py index 636f7d13ef44..eac1265bb50a 100644 --- a/wagtail/admin/views/generic/models.py +++ b/wagtail/admin/views/generic/models.py @@ -677,6 +677,16 @@ def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.action = self.get_action(request) + @cached_property + def object_pk(self): + # Must be a cached_property to prevent this from being re-run on the unquoted + # pk written back by get_object, which would result in it being unquoted again. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + return unquote(str(quoted_pk)) + def get_action(self, request): for action in self.get_available_actions(): if request.POST.get(f"action-{action}"): @@ -687,9 +697,9 @@ def get_available_actions(self): return self.actions def get_object(self, queryset=None): - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + self.kwargs[self.pk_url_kwarg] = self.object_pk return super().get_object(queryset) def get_page_subtitle(self): @@ -947,9 +957,15 @@ def get_object(self, queryset=None): # If the object has already been loaded, return it to avoid another query if getattr(self, "object", None): return self.object - if self.pk_url_kwarg not in self.kwargs: - self.kwargs[self.pk_url_kwarg] = self.args[0] - self.kwargs[self.pk_url_kwarg] = unquote(str(self.kwargs[self.pk_url_kwarg])) + + # SingleObjectMixin.get_object looks for the unquoted pk in self.kwargs, + # so we need to write it back there. + try: + quoted_pk = self.kwargs[self.pk_url_kwarg] + except KeyError: + quoted_pk = self.args[0] + self.kwargs[self.pk_url_kwarg] = unquote(str(quoted_pk)) + return super().get_object(queryset) def get_usage(self):
wagtail
12,741
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 5cdc27de7fb..0f943ca6ab2 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -46,6 +46,7 @@ Changelog * Fix: Fix crash when loading the dashboard with only the "unlock" or "bulk delete" page permissions (Unyime Emmanuel Udoh, Sage Abdullah) * Fix: Improve deprecation warning for `WidgetWithScript` by raising it with `stacklevel=3` (Joren Hammudoglu) * Fix: Correctly place comment buttons next to date / datetime / time fields. (Srishti Jaiswal) + * Fix: Add missing `FilterField("created_at")` to `AbstractDocument` to fix ordering by `created_at` after searching in the documents index view (Srishti Jaiswal) * Docs: Move the model reference page from reference/pages to the references section as it covers all Wagtail core models (Srishti Jaiswal) * Docs: Move the panels reference page from references/pages to the references section as panels are available for any model editing, merge panels API into this page (Srishti Jaiswal) * Docs: Move the tags documentation to standalone advanced topic, instead of being inside the reference/pages section (Srishti Jaiswal) diff --git a/docs/releases/6.4.md b/docs/releases/6.4.md index 9fb788f79a8..dc2d2f58c94 100644 --- a/docs/releases/6.4.md +++ b/docs/releases/6.4.md @@ -58,6 +58,7 @@ depth: 1 * Fix crash when loading the dashboard with only the "unlock" or "bulk delete" page permissions (Unyime Emmanuel Udoh, Sage Abdullah) * Improve deprecation warning for `WidgetWithScript` by raising it with `stacklevel=3` (Joren Hammudoglu) * Correctly place comment buttons next to date / datetime / time fields. (Srishti Jaiswal) + * Add missing `FilterField("created_at")` to `AbstractDocument` to fix ordering by `created_at` after searching in the documents index view (Srishti Jaiswal) ### Documentation diff --git a/wagtail/documents/models.py b/wagtail/documents/models.py index e4ed73ae4b2..8495650374d 100644 --- a/wagtail/documents/models.py +++ b/wagtail/documents/models.py @@ -57,6 +57,7 @@ class AbstractDocument(CollectionMember, index.Indexed, models.Model): ], ), index.FilterField("uploaded_by_user"), + index.FilterField("created_at"), ] def clean(self):
0bba5da337283ff594bf4701072fc2f02177e40b
Add a filter field for the "created_at" property to enable filtering documents by creation date.
The following is the text of a github issue and related comments for this repository: Ordering documents in search causes error <!-- Found a bug? Please fill out the sections below. 👍 --> ### Issue Summary Issue was discovered by editors when searching through uploaded documents with similar names. Attempt to order them by date has failed. ### Steps to Reproduce 1. Login to wagtail admin 2. Search for an existing document 3. In search results click Documents tab 4. Click `Created` to sort the documents 5. Error - Cannot sort search results ### Technical details - Python version: 3.10.15 - Django version: 5.0 - 5.1 - Wagtail version: 6.0.6 - 6.3.1 - Browser version: Chrome 131 ### Working on this Error message suggests adding index.FilterField('created_at') to AbstractDocument model. Adding this line to a local instance in virtual environment has fixed the issue Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/wagtail/documents/models.py b/wagtail/documents/models.py index e4ed73ae4b2..8495650374d 100644 --- a/wagtail/documents/models.py +++ b/wagtail/documents/models.py @@ -57,6 +57,7 @@ class AbstractDocument(CollectionMember, index.Indexed, models.Model): ], ), index.FilterField("uploaded_by_user"), + index.FilterField("created_at"), ] def clean(self):
diff --git a/wagtail/documents/tests/test_admin_views.py b/wagtail/documents/tests/test_admin_views.py index 4711ae8ccad..1554bfd5061 100644 --- a/wagtail/documents/tests/test_admin_views.py +++ b/wagtail/documents/tests/test_admin_views.py @@ -30,6 +30,7 @@ ) from wagtail.test.utils import WagtailTestUtils from wagtail.test.utils.template_tests import AdminTemplateTestUtils +from wagtail.test.utils.timestamps import local_datetime class TestDocumentIndexView(WagtailTestUtils, TestCase): @@ -95,7 +96,7 @@ def test_pagination_out_of_range(self): ) def test_ordering(self): - orderings = ["title", "-created_at"] + orderings = ["title", "created_at", "-created_at"] for ordering in orderings: response = self.get({"ordering": ordering}) self.assertEqual(response.status_code, 200) @@ -371,6 +372,39 @@ def test_tag_filtering_with_search_term(self): response = self.get({"tag": "one", "q": "test"}) self.assertEqual(response.context["page_obj"].paginator.count, 2) + def test_search_and_order_by_created_at(self): + # Create Documents, change their created_at dates after creation as + # the field has auto_now_add=True + doc1 = models.Document.objects.create(title="recent good Document") + doc1.created_at = local_datetime(2024, 1, 1) + doc1.save() + + doc2 = models.Document.objects.create(title="latest ok Document") + doc2.created_at = local_datetime(2025, 1, 1) + doc2.save() + + doc3 = models.Document.objects.create(title="oldest good document") + doc3.created_at = local_datetime(2023, 1, 1) + doc3.save() + + cases = [ + ("created_at", [doc3, doc1]), + ("-created_at", [doc1, doc3]), + ] + + for ordering, expected_docs in cases: + with self.subTest(ordering=ordering): + response = self.get({"q": "good", "ordering": ordering}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.context["query_string"], "good") + + # Check that the documents are filtered by the search query + # and are in the correct order + documents = list(response.context["page_obj"].object_list) + self.assertEqual(documents, expected_docs) + self.assertIn("ordering", response.context) + self.assertEqual(response.context["ordering"], ordering) + class TestDocumentIndexResultsView(WagtailTestUtils, TransactionTestCase): def setUp(self):
diff --git a/wagtail/documents/models.py b/wagtail/documents/models.py index e4ed73ae4b2..8495650374d 100644 --- a/wagtail/documents/models.py +++ b/wagtail/documents/models.py @@ -57,6 +57,7 @@ class AbstractDocument(CollectionMember, index.Indexed, models.Model): i
diff --git a/wagtail/documents/models.py b/wagtail/documents/models.py index e4ed73ae4b2..8495650374d 100644 --- a/wagtail/documents/models.py +++ b/wagtail/documents/models.py @@ -57,6 +57,7 @@ class AbstractDocument(CollectionMember, index.Indexed, models.Model): ], ), index.FilterField("uploaded_by_user"), + index.FilterField("created_at"), ] def clean(self):
junit5
4,201
diff --git a/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java b/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java index 8aed7644f2d8..023dd6fea6d2 100644 --- a/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java +++ b/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java @@ -14,6 +14,7 @@ import static org.junit.platform.commons.support.AnnotationSupport.findRepeatableAnnotations; import java.lang.reflect.Method; +import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; @@ -74,8 +75,13 @@ public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContex ParameterizedTestNameFormatter formatter = createNameFormatter(extensionContext, methodContext); AtomicLong invocationCount = new AtomicLong(0); + List<ArgumentsSource> argumentsSources = findRepeatableAnnotations(methodContext.method, ArgumentsSource.class); + + Preconditions.notEmpty(argumentsSources, + "Configuration error: You must configure at least one arguments source for this @ParameterizedTest"); + // @formatter:off - return findRepeatableAnnotations(methodContext.method, ArgumentsSource.class) + return argumentsSources .stream() .map(ArgumentsSource::value) .map(clazz -> ParameterizedTestSpiInstantiator.instantiate(ArgumentsProvider.class, clazz, extensionContext))
16c6f72c1c728c015e35cb739ea75884f19f990c
Check that there is at least one arguments source configured, and fail with the message "Configuration error: You must configure at least one arguments source for this @ParameterizedTest" if none are found.
The following is the text of a github issue and related comments for this repository: Fail `@ParameterizedTest` if there is no registered `ArgumentProvider` Not declaring any `@...Source` annotation on a `@ParameterizedTest` method is most likely a user error and should be surfaced as a test failure rather than being silently ignored (now that #1477 permits zero invocations). ## Deliverables - [x] Check that there's at least one `ArgumentProvider` registered in `ParameterizedTestExtension` and fail the container otherwise Resolve the issue described above. Do not modify tests or user code. The issue can be resolved by modifying the actual library/application code. Make the minimal changes to resolve the issue while adhering to the specification and coding style of the codebase.
diff --git a/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java b/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java index 8aed7644f2d8..023dd6fea6d2 100644 --- a/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java +++ b/junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedTestExtension.java @@ -14,6 +14,7 @@ import static org.junit.platform.commons.support.AnnotationSupport.findRepeatableAnnotations; import java.lang.reflect.Method; +import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; @@ -74,8 +75,13 @@ public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContex ParameterizedTestNameFormatter formatter = createNameFormatter(extensionContext, methodContext); AtomicLong invocationCount = new AtomicLong(0); + List<ArgumentsSource> argumentsSources = findRepeatableAnnotations(methodContext.method, ArgumentsSource.class); + + Preconditions.notEmpty(argumentsSources, + "Configuration error: You must configure at least one arguments source for this @ParameterizedTest"); + // @formatter:off - return findRepeatableAnnotations(methodContext.method, ArgumentsSource.class) + return argumentsSources .stream() .map(ArgumentsSource::value) .map(clazz -> ParameterizedTestSpiInstantiator.instantiate(ArgumentsProvider.class, clazz, extensionContext))
diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java index 638cdbf95e1f..fbdf70e080c7 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java @@ -146,16 +146,23 @@ void throwsExceptionWhenParameterizedTestIsNotInvokedAtLeastOnce() { @Test void doesNotThrowExceptionWhenParametrizedTestDoesNotRequireArguments() { - var extensionContextWithAnnotatedTestMethod = getExtensionContextReturningSingleMethod( - new TestCaseAllowNoArgumentsMethod()); + var extensionContext = getExtensionContextReturningSingleMethod(new TestCaseAllowNoArgumentsMethod()); - var stream = this.parameterizedTestExtension.provideTestTemplateInvocationContexts( - extensionContextWithAnnotatedTestMethod); + var stream = this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext); // cause the stream to be evaluated stream.toArray(); stream.close(); } + @Test + void throwsExceptionWhenParameterizedTestHasNoArgumentsSource() { + var extensionContext = getExtensionContextReturningSingleMethod(new TestCaseWithNoArgumentsSource()); + + assertThrows(PreconditionViolationException.class, + () -> this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext), + "Configuration error: You must configure at least one arguments source for this @ParameterizedTest"); + } + @Test void throwsExceptionWhenArgumentsProviderIsNotStatic() { var extensionContextWithAnnotatedTestMethod = getExtensionContextReturningSingleMethod( @@ -323,8 +330,8 @@ void method() { static class TestCaseWithAnnotatedMethod { - @SuppressWarnings("JUnitMalformedDeclaration") @ParameterizedTest + @ArgumentsSource(ZeroArgumentsProvider.class) void method() { } } @@ -332,10 +339,27 @@ void method() { static class TestCaseAllowNoArgumentsMethod { @ParameterizedTest(allowZeroInvocations = true) + @ArgumentsSource(ZeroArgumentsProvider.class) void method() { } } + static class TestCaseWithNoArgumentsSource { + + @ParameterizedTest(allowZeroInvocations = true) + @SuppressWarnings("JUnitMalformedDeclaration") + void method() { + } + } + + static class ZeroArgumentsProvider implements ArgumentsProvider { + + @Override + public Stream<? extends Arguments> provideArguments(ExtensionContext context) { + return Stream.empty(); + } + } + static class ArgumentsProviderWithCloseHandlerTestCase { @ParameterizedTest diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java index 13739ea4e018..ad28cd7fa555 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java @@ -457,7 +457,7 @@ void failsWhenArgumentsRequiredButNoneProvided() { } @Test - void failsWhenArgumentsAreNotRequiredAndNoneProvided() { + void doesNotFailWhenArgumentsAreNotRequiredAndNoneProvided() { var result = execute(ZeroArgumentsTestCase.class, "testThatDoesNotRequireArguments", String.class); result.allEvents().assertEventsMatchExactly( // event(engine(), started()), event(container(ZeroArgumentsTestCase.class), started()), @@ -467,6 +467,15 @@ void failsWhenArgumentsAreNotRequiredAndNoneProvided() { event(engine(), finishedSuccessfully())); } + @Test + void failsWhenNoArgumentsSourceIsDeclared() { + var result = execute(ZeroArgumentsTestCase.class, "testThatHasNoArgumentsSource", String.class); + result.containerEvents().assertThatEvents() // + .haveExactly(1, // + event(displayName("testThatHasNoArgumentsSource(String)"), finishedWithFailure(message( + "Configuration error: You must configure at least one arguments source for this @ParameterizedTest")))); + } + private EngineExecutionResults execute(DiscoverySelector... selectors) { return EngineTestKit.engine(new JupiterTestEngine()).selectors(selectors).execute(); } @@ -2428,6 +2437,12 @@ void testThatDoesNotRequireArguments(String argument) { fail("This test should not be executed, because no arguments are provided."); } + @ParameterizedTest(allowZeroInvocations = true) + @SuppressWarnings("JUnitMalformedDeclaration") + void testThatHasNoArgumentsSource(String argument) { + fail("This test should not be executed, because no arguments source is declared."); + } + public static Stream<Arguments> zeroArgumentsProvider() { return Stream.empty(); }
null
null
End of preview. Expand in Data Studio

LiveSWEBench Tasks

This dataset contains all task instances for the LiveSWEBench benchmark. Tasks are stored in the following format:

  1. repo_name (str): the name of the repository for this task
  2. task_num (int): the original PR number for the task, used now as an identifier
  3. gold_patch (str): the actual changes made in the PR to resolve the issue in this task
  4. test_patch (str): the changes made to test files to validate the task solution
  5. edit_patch (str): a subset of the gold patch containing changes to just one file
  6. autocomplete_patch (str): a subset of hunks from the gold patch for the autocomplete task
  7. prompt (str): the prompt for the agent task
  8. edit_prompt (str): the prompt used for the edit task
  9. autocopmlete_prompts (str): one line snippet for each hunk in autocomplete_patch, to be pasted to trigger the autocomplete
  10. commit (str): the base commit hash for the task
Downloads last month
275

Collection including livebench/liveswebench