Skip to content

Commit d0cf701

Browse files
committed
Better accessing to context request.
1 parent f869214 commit d0cf701

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

djangocms_frontend/templatetags/frontend.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import typing
3+
import uuid
34

45
from classytags.arguments import Argument, MultiKeywordArgument
56
from classytags.core import Options, Tag
@@ -11,6 +12,7 @@
1112
from django.contrib.contenttypes.models import ContentType
1213
from django.core.serializers.json import DjangoJSONEncoder
1314
from django.db import models
15+
from django.http import HttpRequest
1416
from django.template.defaultfilters import safe
1517
from django.utils.encoding import force_str
1618
from django.utils.functional import Promise
@@ -77,11 +79,14 @@ def get_attributes(attribute_field, *add_classes):
7779
@register.simple_tag(takes_context=True)
7880
def set_html_id(context: template.Context, instance: FrontendUIItem) -> str:
7981
if instance.html_id is None:
80-
request = context["request"]
81-
key = "frontend_plugins_counter"
82-
counter = getattr(request, key, 0) + 1
83-
instance.html_id = f"frontend-plugins-{counter}"
84-
setattr(request, key, counter)
82+
request = context.get("request")
83+
if isinstance(request, HttpRequest):
84+
key = "frontend_plugins_counter"
85+
counter = getattr(request, key, 0) + 1
86+
instance.html_id = f"frontend-plugins-{counter}"
87+
setattr(request, key, counter)
88+
else:
89+
instance.html_id = f"uuid4={uuid.uuid4()}"
8590
return instance.html_id
8691

8792

tests/collapse/test_plugins.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
from unittest.mock import patch
2+
13
from cms.api import add_plugin
24
from cms.test_utils.testcases import CMSTestCase
5+
from django.template import Context
36

47
from djangocms_frontend.contrib.collapse.cms_plugins import (
58
CollapseContainerPlugin,
@@ -11,6 +14,8 @@
1114
CollapseForm,
1215
CollapseTriggerForm,
1316
)
17+
from djangocms_frontend.models import FrontendUIItem
18+
from djangocms_frontend.templatetags.frontend import set_html_id
1419

1520
from ..fixtures import TestFixture
1621

@@ -99,3 +104,12 @@ def create_plugin():
99104
response,
100105
"""<div id="collapse-frontend-plugins-2" data-bs-children=".card" role="tablist"></div>""",
101106
html=True)
107+
108+
def test_set_html_id(self):
109+
instance = FrontendUIItem()
110+
context = Context()
111+
with patch("os.urandom", lambda n: b'\x1bB\x96\xabyI\xf6`\xd0\xc0,\xf8\x83\xe8,\xb8'):
112+
html_id = set_html_id(context, instance)
113+
identifier = "uuid4=1b4296ab-7949-4660-90c0-2cf883e82cb8"
114+
self.assertEqual(html_id, identifier)
115+
self.assertEqual(instance.html_id, identifier)

0 commit comments

Comments
 (0)