Skip to content

Commit e58e78b

Browse files
Fix utils.get_name_from_obj proper view names (#1846)
1 parent d4cfadc commit e58e78b

File tree

3 files changed

+20
-10
lines changed

3 files changed

+20
-10
lines changed

debug_toolbar/utils.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,15 @@ def get_template_source_from_exception_info(
162162

163163

164164
def get_name_from_obj(obj: Any) -> str:
165-
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
166-
167-
if hasattr(obj, "__module__"):
168-
module = obj.__module__
169-
name = f"{module}.{name}"
170-
171-
return name
165+
"""Get the best name as `str` from a view or a object."""
166+
# This is essentially a rewrite of the `django.contrib.admindocs.utils.get_view_name`
167+
# https://github.com/django/django/blob/9a22d1769b042a88741f0ff3087f10d94f325d86/django/contrib/admindocs/utils.py#L26-L32
168+
if hasattr(obj, "view_class"):
169+
klass = obj.view_class
170+
return f"{klass.__module__}.{klass.__qualname__}"
171+
mod_name = obj.__module__
172+
view_name = getattr(obj, "__qualname__", obj.__class__.__name__)
173+
return mod_name + "." + view_name
172174

173175

174176
def getframeinfo(frame: Any, context: int = 1) -> inspect.Traceback:

docs/changes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Pending
1212
* Fixed template panel to avoid evaluating ``LazyObject`` when not already
1313
evaluated.
1414
* Added support for Django 5.0.
15+
* Refactor the ``utils.get_name_from_obj`` to simulate the behavior of
16+
``django.contrib.admindocs.utils.get_view_name``.
1517

1618
4.2.0 (2023-08-10)
1719
------------------

tests/test_utils.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,24 @@ def x():
1818
return 1
1919

2020
res = get_name_from_obj(x)
21-
self.assertEqual(res, "tests.test_utils.x")
21+
self.assertEqual(
22+
res, "tests.test_utils.GetNameFromObjTestCase.test_func.<locals>.x"
23+
)
2224

2325
def test_lambda(self):
2426
res = get_name_from_obj(lambda: 1)
25-
self.assertEqual(res, "tests.test_utils.<lambda>")
27+
self.assertEqual(
28+
res, "tests.test_utils.GetNameFromObjTestCase.test_lambda.<locals>.<lambda>"
29+
)
2630

2731
def test_class(self):
2832
class A:
2933
pass
3034

3135
res = get_name_from_obj(A)
32-
self.assertEqual(res, "tests.test_utils.A")
36+
self.assertEqual(
37+
res, "tests.test_utils.GetNameFromObjTestCase.test_class.<locals>.A"
38+
)
3339

3440

3541
class RenderStacktraceTestCase(unittest.TestCase):

0 commit comments

Comments
 (0)