Skip to content

fix: Allow lazy wizard initialization #8266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

fsbraun
Copy link
Member

@fsbraun fsbraun commented Jun 28, 2025

Description

This is a port forward of #8265. This PR fixes two issues:

  • Since Django 5.1 accessing the database during app initialization is discouraged. Since cms_config runs during app initialization, wizards needing, e.g., some config from the db, need to be able to initialize lazily.
  • When on an app-hooked page, the wizards were not accessible (i.e, always disabled). This is particularly confusing, since the apphooked app might have registered its own wizard, e.g, djangocms-stories wizard should be available when viewing a post.

Related resources

Checklist

  • I have opened this pull request against main
  • I have added or modified the tests when changing logic
  • I have followed the conventional commits guidelines to add meaningful information into the changelog
  • I have read the contribution guidelines and I have joined the channel #pr-reviews on our Discord Server to find a “pr review buddy” who is going to review my pull request.

Summary by Sourcery

Implement lazy wizard initialization in CMSCoreExtensions, add new wizard_base APIs for retrieving and managing wizards, deprecate the legacy helpers and WizardPool interfaces, update toolbar logic to use the new API, and adjust tests accordingly

New Features:

  • Allow lazy initialization of wizards by deferring instantiation of all cms_wizards until accessed via a cached property
  • Introduce global functions for wizard management: get_entries, get_entry, entry_choices, and clear_wizard_cache

Enhancements:

  • Deprecate the old helpers and WizardPool interface with compatibility warnings
  • Simplify the toolbar wizard button logic to use the new entry_choices API

Tests:

  • Adjust tests to reset and access the lazily evaluated wizards and to expect configuration exceptions on invalid wizard definitions

Chores:

fsbraun and others added 2 commits June 28, 2025 15:54
* fix: Allow lazy wizard initialization

* Update cms/cms_toolbars.py

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

* Update cms/cms_config.py

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Copy link
Contributor

sourcery-ai bot commented Jun 28, 2025

Reviewer's Guide

This PR ports forward lazy wizard initialization by deferring wizard registration in CMSCoreExtensions via a cached_property, adding new registry helper functions, deprecating legacy helpers and WizardPool methods, and updating related tests and toolbar logic.

Sequence diagram for lazy wizard initialization and access

sequenceDiagram
    participant App as Django App
    participant CMSConfig as CMSCoreConfig
    participant Extension as CMSCoreExtensions
    participant User as User
    participant Wizard as Wizard

    App->>CMSConfig: Load cms_wizards
    CMSConfig->>Extension: configure_wizards(cms_config)
    Extension->>Extension: lazy_wizards.append(cms_config.cms_wizards)
    User->>Extension: Access wizards property
    Extension->>Extension: Build wizards dict from lazy_wizards
    Extension->>User: Return wizards dict
Loading

Class diagram for deprecated helpers and WizardPool

classDiagram
    class helpers {
        +get_entries() <<deprecated>>
        +get_entry(entry_key) <<deprecated>>
    }
    class WizardPool {
        +register(entry)
        +is_registered(entry, passive)
    }
    helpers ..> wizard_base : now delegates
    WizardPool ..> Wizard : uses
Loading

File-Level Changes

Change Details Files
Introduce standalone wizard registry API functions
  • Add get_entries() to list registered wizards by weight
  • Add get_entry() to retrieve a wizard by ID
  • Add entry_choices() to yield permitted wizards per user/page
  • Add clear_wizard_cache() to reset the wizard registry
cms/wizards/wizard_base.py
Switch CMSCoreExtensions to lazy wizard loading
  • Replace immediate wizards dict with lazy_wizards list
  • configure_wizards() now appends cms_wizards iterables
  • Implement @cached_property wizards to build/merge dict on access
  • Enforce Wizard instance checks and raise on invalid types
cms/cms_config.py
Deprecate legacy wizard helpers with warning
  • Remove direct get_entries/get_entry definitions
  • Re-export new functions from wizard_base
  • Emit RemovedInDjangoCMS51Warning on import
cms/wizards/helpers.py
Streamline and deprecate WizardPool usage
  • Remove local entry_choices implementation; import new one
  • Import Wizard and entry_choices for backwards compatibility
  • Add deprecation warning in register() for WizardPool usage
cms/wizards/wizard_pool.py
Align tests for lazy wizard initialization
  • Invoke extensions.wizards to trigger lazy loading in tests
  • Reset cached_property in teardown by deleting extension.wizards
  • Remove obsolete warning-based registration test
  • Import apps where needed for registry checks
cms/tests/test_cms_config_wizards.py
cms/tests/test_wizards.py
Simplify toolbar wizard button logic
  • Unify user and page_pk assignment into single block
  • Compute disabled state via not list(entry_choices(...))
cms/cms_toolbars.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @fsbraun - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `cms/wizards/wizard_base.py:30` </location>
<code_context>
+            # do something with a wizard...
+    """
+    wizards = apps.get_app_config('cms').cms_extension.wizards
+    return sorted(wizards.values(), key=lambda e: e.weight)
+
+
</code_context>

<issue_to_address>
Sorting now returns only values, not (id, wizard) tuples.

The return type no longer matches the docstring and example, which may break code relying on the previous (id, wizard) tuple format.
</issue_to_address>

### Comment 2
<location> `cms/cms_config.py:51` </location>
<code_context>
+        """
+
+        wizards = {}
+        for iterable in self.lazy_wizards:
+            new_wizards = {wizard.id: wizard for wizard in iterable}
+            if wizard := next((wizard for wizard in new_wizards.values() if not isinstance(wizard, Wizard)), None):
+                # If any wizard in the iterable is not an instance of Wizard, raise an exception
                 raise ImproperlyConfigured(
-                    "All wizards defined in cms_wizards must inherit "
-                    "from cms.wizards.wizard_base.Wizard"
+                    f"cms_wizards must be iterable of Wizard instances, got {type(wizard)}"
                 )
-            elif wizard.id in self.wizards:
-                msg = f"Wizard for model {wizard.get_model()} has already been registered"
-                logger.warning(msg)
-            else:
-                self.wizards[wizard.id] = wizard
+            wizards |= new_wizards
+        return wizards

</code_context>

<issue_to_address>
Merging dictionaries with |= may overwrite Wizards with duplicate IDs.

This can lead to unintentional data loss. Please add a check for duplicate IDs and raise an error or warning if found.

Suggested implementation:

```python
        wizards = {}

```

```python
        for iterable in self.lazy_wizards:
            new_wizards = {wizard.id: wizard for wizard in iterable}
            if wizard := next((wizard for wizard in new_wizards.values() if not isinstance(wizard, Wizard)), None):
                # If any wizard in the iterable is not an instance of Wizard, raise an exception
                raise ImproperlyConfigured(
                    f"cms_wizards must be iterable of Wizard instances, got {type(wizard)}"
                )
            duplicate_ids = set(new_wizards.keys()) & set(wizards.keys())
            if duplicate_ids:
                raise ImproperlyConfigured(
                    f"Duplicate wizard IDs found: {', '.join(str(i) for i in duplicate_ids)}"
                )
            wizards |= new_wizards
        return wizards

```
</issue_to_address>

### Comment 3
<location> `cms/tests/test_cms_config_wizards.py:52` </location>
<code_context>
         wizard = Mock(id=3, spec=object)
         cms_config = Mock(
             cms_enabled=True, cms_wizards=[wizard])
+        extensions.configure_wizards(cms_config)
         with self.assertRaises(ImproperlyConfigured):
-            extensions.configure_wizards(cms_config)
+            extensions.wizards
+

</code_context>

<issue_to_address>
Test for exception when non-Wizard instance is present now triggers on property access.

Consider adding a comment or separate test to document that the exception is now raised on 'wizards' property access, not during configuration, to clarify intent and timing.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        wizard = Mock(id=3, spec=object)
        cms_config = Mock(
            cms_enabled=True, cms_wizards=[wizard])
        extensions.configure_wizards(cms_config)
        with self.assertRaises(ImproperlyConfigured):
            extensions.wizards

=======
        # Note: Exception is now raised on 'wizards' property access, not during configuration.
        wizard = Mock(id=3, spec=object)
        cms_config = Mock(
            cms_enabled=True, cms_wizards=[wizard])
        extensions.configure_wizards(cms_config)
        with self.assertRaises(ImproperlyConfigured):
            extensions.wizards

    def test_raises_exception_on_wizards_property_access_with_non_wizard(self):
        """
        Test that ImproperlyConfigured is raised when a non-Wizard instance is present,
        and that the exception is triggered on 'wizards' property access, not during configuration.
        """
        wizard = Mock(id=3, spec=object)
        cms_config = Mock(
            cms_enabled=True, cms_wizards=[wizard])
        extensions.configure_wizards(cms_config)
        with self.assertRaises(ImproperlyConfigured):
            _ = extensions.wizards
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 49 to +55
wizard = Mock(id=3, spec=object)
cms_config = Mock(
cms_enabled=True, cms_wizards=[wizard])
extensions.configure_wizards(cms_config)
with self.assertRaises(ImproperlyConfigured):
extensions.configure_wizards(cms_config)
extensions.wizards

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Test for exception when non-Wizard instance is present now triggers on property access.

Consider adding a comment or separate test to document that the exception is now raised on 'wizards' property access, not during configuration, to clarify intent and timing.

Suggested change
wizard = Mock(id=3, spec=object)
cms_config = Mock(
cms_enabled=True, cms_wizards=[wizard])
extensions.configure_wizards(cms_config)
with self.assertRaises(ImproperlyConfigured):
extensions.configure_wizards(cms_config)
extensions.wizards
# Note: Exception is now raised on 'wizards' property access, not during configuration.
wizard = Mock(id=3, spec=object)
cms_config = Mock(
cms_enabled=True, cms_wizards=[wizard])
extensions.configure_wizards(cms_config)
with self.assertRaises(ImproperlyConfigured):
extensions.wizards
def test_raises_exception_on_wizards_property_access_with_non_wizard(self):
"""
Test that ImproperlyConfigured is raised when a non-Wizard instance is present,
and that the exception is triggered on 'wizards' property access, not during configuration.
"""
wizard = Mock(id=3, spec=object)
cms_config = Mock(
cms_enabled=True, cms_wizards=[wizard])
extensions.configure_wizards(cms_config)
with self.assertRaises(ImproperlyConfigured):
_ = extensions.wizards

@fsbraun fsbraun force-pushed the feat/extended-wizard branch from e47f647 to 664dcf7 Compare June 28, 2025 14:10
@fsbraun fsbraun changed the title feat: Allow lazy wizard initialization fix: Allow lazy wizard initialization Jun 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant