Skip to content

Commit

Permalink
ci: auto fixes from pre-commit hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jun 20, 2024
1 parent cdf3bfa commit da34c01
Show file tree
Hide file tree
Showing 19 changed files with 126 additions and 216 deletions.
19 changes: 8 additions & 11 deletions aldryn_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,14 @@ def to_settings(self, data, settings):
env = partial(djsenv, settings=settings)

# Get a migration user if the env setting has been added
migration_user_id = env(
'DJANGOCMS_SNIPPET_VERSIONING_MIGRATION_USER_ID',
default=False
)
migration_user_id = env("DJANGOCMS_SNIPPET_VERSIONING_MIGRATION_USER_ID", default=False)
if migration_user_id:
settings['DJANGOCMS_SNIPPET_VERSIONING_MIGRATION_USER_ID'] = int(migration_user_id)
settings["DJANGOCMS_SNIPPET_VERSIONING_MIGRATION_USER_ID"] = int(migration_user_id)

if data['editor_theme']:
settings['DJANGOCMS_SNIPPET_THEME'] = data['editor_theme']
if data['editor_mode']:
settings['DJANGOCMS_SNIPPET_MODE'] = data['editor_mode']
if data['enable_search']:
settings['DJANGOCMS_SNIPPET_SEARCH'] = data['enable_search']
if data["editor_theme"]:
settings["DJANGOCMS_SNIPPET_THEME"] = data["editor_theme"]
if data["editor_mode"]:
settings["DJANGOCMS_SNIPPET_MODE"] = data["editor_mode"]
if data["enable_search"]:
settings["DJANGOCMS_SNIPPET_SEARCH"] = data["enable_search"]
return settings
41 changes: 11 additions & 30 deletions src/djangocms_snippet/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@

# Use the version mixin if djangocms-versioning is installed and enabled
snippet_admin_classes = [admin.ModelAdmin]
djangocms_versioning_enabled = getattr(
settings, "DJANGOCMS_SNIPPET_VERSIONING_ENABLED", True
)
djangocms_versioning_enabled = getattr(settings, "DJANGOCMS_SNIPPET_VERSIONING_ENABLED", True)

try:
try:
Expand Down Expand Up @@ -56,9 +54,7 @@ class Media:
"data-theme": getattr(settings, "DJANGOCMS_SNIPPET_MODE", "github"),
}
form = SnippetForm
formfield_overrides: ClassVar[dict] = {
models.TextField: {"widget": Textarea(attrs=text_area_attrs)}
}
formfield_overrides: ClassVar[dict] = {models.TextField: {"widget": Textarea(attrs=text_area_attrs)}}
# This was move here from model, otherwise first() and last() return the same when handling grouper queries
ordering = ("name",)

Expand Down Expand Up @@ -101,41 +97,29 @@ def get_list_display_links(self, request, list_display):
self.list_display_links = (None,)
return self.list_display_links

def preview_view(
self, request, snippet_id=None, form_url="", extra_context=None
):
def preview_view(self, request, snippet_id=None, form_url="", extra_context=None):
"""
Custom preview endpoint to display a change form in read only mode
Solution based on django changeform view implementation
https://github.com/django/django/blob/4b8e9492d9003ca357a4402f831112dd72efd2f8/django/contrib/admin/options.py#L1553
"""
to_field = request.POST.get(
TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)
)
to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))

if to_field and not self.to_field_allowed(request, to_field):
raise DisallowedModelAdminToField(
f"The field {to_field} cannot be referenced."
)
raise DisallowedModelAdminToField(f"The field {to_field} cannot be referenced.")

model = self.model
opts = model._meta

obj = self.get_object(request, unquote(str(snippet_id)), to_field)

if obj is None:
return self._get_obj_does_not_exist_redirect(
request, opts, str(snippet_id)
)
return self._get_obj_does_not_exist_redirect(request, opts, str(snippet_id))

fieldsets = self.get_fieldsets(request, obj)
model_form = self.get_form(
request, obj, change=False, fields=flatten_fieldsets(fieldsets)
)
model_form = self.get_form(request, obj, change=False, fields=flatten_fieldsets(fieldsets))
form = model_form(instance=obj)
formsets, inline_instances = self._create_formsets(
request, obj, change=True
)
formsets, inline_instances = self._create_formsets(request, obj, change=True)

readonly_fields = flatten_fieldsets(fieldsets)

Expand All @@ -149,9 +133,7 @@ def preview_view(
)
media = self.media + admin_form.media

inline_formsets = self.get_inline_formsets(
request, formsets, inline_instances, obj
)
inline_formsets = self.get_inline_formsets(request, formsets, inline_instances, obj)
for inline_formset in inline_formsets:
media = media + inline_formset.media

Expand All @@ -163,8 +145,7 @@ def preview_view(
"adminform": admin_form,
"object_id": snippet_id,
"original": obj,
"is_popup": IS_POPUP_VAR in request.POST
or IS_POPUP_VAR in request.GET,
"is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,
"to_field": to_field,
"media": media,
"inline_admin_formsets": inline_formsets,
Expand All @@ -188,7 +169,7 @@ def get_urls(self):
path(
"<int:snippet_id>/preview/",
self.admin_site.admin_view(self.preview_view),
name=f"{self.model._meta.app_label}_{self.model._meta.model_name}_preview"
name=f"{self.model._meta.app_label}_{self.model._meta.model_name}_preview",
),
*super().get_urls(),
]
Expand Down
8 changes: 2 additions & 6 deletions src/djangocms_snippet/cms_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,8 @@


class SnippetCMSAppConfig(CMSAppConfig):
djangocms_versioning_enabled = getattr(
settings, "DJANGOCMS_SNIPPET_VERSIONING_ENABLED", True
)
djangocms_moderation_enabled = getattr(
settings, "DJANGOCMS_SNIPPET_MODERATION_ENABLED", True
)
djangocms_versioning_enabled = getattr(settings, "DJANGOCMS_SNIPPET_VERSIONING_ENABLED", True)
djangocms_moderation_enabled = getattr(settings, "DJANGOCMS_SNIPPET_MODERATION_ENABLED", True)

cms_enabled = True
# cms toolbar enabled to allow for versioning compare view
Expand Down
4 changes: 1 addition & 3 deletions src/djangocms_snippet/cms_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def render(self, context, instance, placeholder):
t = template.Template(snippet.html)
content = t.render(context)
except template.TemplateDoesNotExist:
content = _("Template %(template)s does not exist.") % {
"template": snippet.template
}
content = _("Template %(template)s does not exist.") % {"template": snippet.template}
except Exception as e:
content = escape(str(e))

Expand Down
11 changes: 3 additions & 8 deletions src/djangocms_snippet/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,13 @@ def clean(self):
snippet_queryset = Snippet.objects.all()

if djangocms_versioning_enabled and is_versioning_installed and snippet_grouper:
snippet_queryset = snippet_queryset.exclude(snippet_grouper=snippet_grouper)
snippet_queryset = snippet_queryset.exclude(snippet_grouper=snippet_grouper)

for snippet in snippet_queryset:
if snippet.name == name:
self.add_error(
"name", _("A Snippet with this name already exists")
)
self.add_error("name", _("A Snippet with this name already exists"))
elif snippet.slug == slug:
self.add_error(
"slug", _("A Snippet with this slug already exists")
)
self.add_error("slug", _("A Snippet with this slug already exists"))

return data

Expand All @@ -63,7 +59,6 @@ def save(self, **kwargs):


class SnippetPluginForm(forms.ModelForm):

class Meta:
model = SnippetPtr
fields = ("cmsplugin_ptr", "snippet_grouper")
Expand Down
8 changes: 2 additions & 6 deletions src/djangocms_snippet/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,7 @@ class Snippet(models.Model):
default="",
max_length=255,
)
site = models.ForeignKey(
Site, on_delete=models.CASCADE, null=True, blank=True
)
site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True)

objects = models.Manager()
admin_manager = AdminQuerySet.as_manager()
Expand Down Expand Up @@ -131,9 +129,7 @@ class SnippetPtr(CMSPlugin):
search_fields = ["snippet__html"] if SEARCH_ENABLED else []

def get_short_description(self):
snippet_label = SnippetGrouper.objects.filter(
pk=self.snippet_grouper.pk
).first()
snippet_label = SnippetGrouper.objects.filter(pk=self.snippet_grouper.pk).first()
return snippet_label

class Meta:
Expand Down
4 changes: 2 additions & 2 deletions src/djangocms_snippet/rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@


def render_snippet(request, snippet):
template = 'djangocms_snippet/admin/preview.html'
context = {'snippet': snippet}
template = "djangocms_snippet/admin/preview.html"
context = {"snippet": snippet}
return TemplateResponse(request, template, context)
12 changes: 3 additions & 9 deletions src/djangocms_snippet/templatetags/snippet_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def render(self, context):
elif isinstance(snippet_instance, int): # pragma: no cover
snippet_instance = Snippet.objects.get(pk=snippet_instance)

return mark_safe(
self.get_content_render(context, snippet_instance)
)
return mark_safe(self.get_content_render(context, snippet_instance))

# Rely on the fact that manager something went wrong
# render the fallback template
Expand All @@ -100,9 +98,7 @@ def get_content_render(self, context, instance):
t = template.Template(instance.html)
content = t.render(context)
except template.TemplateDoesNotExist:
content = _("Template %(template)s does not exist.") % {
"template": instance.template
}
content = _("Template %(template)s does not exist.") % {"template": instance.template}
except Exception as e: # pragma: no cover
content = escape(str(e))
if self.parse_until:
Expand All @@ -127,9 +123,7 @@ def do_snippet_fragment(parser, token):
"""
args = token.split_contents()
if len(args) < EXPECTED_LENGTH:
raise template.TemplateSyntaxError(
'You need to specify at least a "snippet" ID, slug or instance'
)
raise template.TemplateSyntaxError('You need to specify at least a "snippet" ID, slug or instance')
if "or" in args:
# Catch contents between tags and pass to renderer
args.append(parser.parse(("endsnippet_fragment",)))
Expand Down
4 changes: 1 addition & 3 deletions src/djangocms_snippet/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,4 @@ def show_draft_content(request=None):
if not request:
return False
request_toolbar = get_toolbar_from_request(request)
return request_toolbar.edit_mode_active or getattr(
request_toolbar, "preview_mode_active", True
)
return request_toolbar.edit_mode_active or getattr(request_toolbar, "preview_mode_active", True)
36 changes: 18 additions & 18 deletions tests/settings.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
#!/usr/bin/env python

try:
import djangocms_versioning #NOQA: F401
import djangocms_versioning # NOQA: F401

add_apps = ['djangocms_versioning']
add_apps = ["djangocms_versioning"]
except ImportError:
add_apps = []

HELPER_SETTINGS = {
'SECRET_KEY': "djangocmssnippetstestsuitekey",
'INSTALLED_APPS': [
'tests.utils',
'djangocms_snippet',
"SECRET_KEY": "djangocmssnippetstestsuitekey",
"INSTALLED_APPS": [
"tests.utils",
"djangocms_snippet",
*add_apps,
],
'CMS_LANGUAGES': {
1: [{
'code': 'en',
'name': 'English',
}]
"CMS_LANGUAGES": {
1: [
{
"code": "en",
"name": "English",
}
]
},
'LANGUAGE_CODE': 'en',
'ALLOWED_HOSTS': ['localhost'],
'DJANGOCMS_SNIPPET_VERSIONING_ENABLED': True,
'DJANGOCMS_SNIPPET_MODERATION_ENABLED': True,
'CMS_TEMPLATES': (
("page.html", "Normal page"),
),
"LANGUAGE_CODE": "en",
"ALLOWED_HOSTS": ["localhost"],
"DJANGOCMS_SNIPPET_VERSIONING_ENABLED": True,
"DJANGOCMS_SNIPPET_MODERATION_ENABLED": True,
"CMS_TEMPLATES": (("page.html", "Normal page"),),
"DEFAULT_AUTO_FIELD": "django.db.models.AutoField",
"CMS_CONFIRM_VERSION4": True,
}
Expand Down
Loading

0 comments on commit da34c01

Please sign in to comment.