Skip to content

Commit 4ea5d1f

Browse files
feat: enable add button on the SnippetPluginForm
Allows creation of a new Snippet when adding a snippet plugin to a page
1 parent 5f7ff3e commit 4ea5d1f

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

djangocms_snippet/cms_plugins.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from cms.plugin_base import CMSPluginBase
88
from cms.plugin_pool import plugin_pool
99

10+
from .forms import SnippetPluginForm
1011
from .models import SnippetPtr
1112
from .utils import show_draft_content
1213

@@ -21,6 +22,7 @@ class SnippetPlugin(CMSPluginBase):
2122
text_enabled = True
2223
text_editor_preview = False
2324
cache = CACHE_ENABLED
25+
form = SnippetPluginForm
2426

2527
def render(self, context, instance, placeholder):
2628
snippet = instance.snippet_grouper.snippet(show_editable=show_draft_content(context["request"]))

djangocms_snippet/forms.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
from cms.utils.urlutils import admin_reverse
12
from django import forms
3+
from django.contrib import admin
24
from django.db import transaction
35
from django.utils.translation import ugettext_lazy as _
46

57
from djangocms_snippet.cms_config import SnippetCMSAppConfig
6-
from djangocms_snippet.models import Snippet, SnippetGrouper
7-
8+
from djangocms_snippet.models import Snippet, SnippetGrouper, SnippetPtr
89

910
try:
1011
from djangocms_versioning import __version__ # NOQA
@@ -64,3 +65,26 @@ def save(self, **kwargs):
6465
if commit:
6566
snippet.save()
6667
return snippet
68+
69+
70+
class SnippetPluginForm(forms.ModelForm):
71+
72+
class Meta:
73+
model = SnippetPtr
74+
fields = ("cmsplugin_ptr", "snippet_grouper")
75+
76+
def __init__(self, *args, **kwargs):
77+
"""
78+
Initialise the form with the add button enabled to allow adding a new snippet from the plugin form. To enable
79+
this the get_related_url method on the widget is monkey patched to build a URL for the Snippet admin instead of
80+
the SnippetGrouper, as this is not enabled in the admin.
81+
"""
82+
super(SnippetPluginForm, self).__init__(*args, **kwargs)
83+
self.fields["snippet_grouper"].widget.can_add_related = True
84+
self.fields["snippet_grouper"].widget.get_related_url = self.get_related_url_for_snippet
85+
86+
def get_related_url_for_snippet(self, info, action, *args):
87+
"""
88+
Build URL to the Snippet admin for the given action
89+
"""
90+
return admin_reverse(f"djangocms_snippet_snippet_{action}", current_app=admin.site.name, args=args)

0 commit comments

Comments
 (0)