Skip to content

Fix utils.get_name_from_obj proper view names #1846

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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions debug_toolbar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,15 @@ def get_template_source_from_exception_info(


def get_name_from_obj(obj: Any) -> str:
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__

if hasattr(obj, "__module__"):
module = obj.__module__
name = f"{module}.{name}"

return name
"""Get the best name as `str` from a view or a object."""
# This is essentially a rewrite of the `django.contrib.admindocs.utils.get_view_name`
# https://github.com/django/django/blob/9a22d1769b042a88741f0ff3087f10d94f325d86/django/contrib/admindocs/utils.py#L26-L32
if hasattr(obj, "view_class"):
klass = obj.view_class
return f"{klass.__module__}.{klass.__qualname__}"
mod_name = obj.__module__
view_name = getattr(obj, "__qualname__", obj.__class__.__name__)
return mod_name + "." + view_name


def getframeinfo(frame: Any, context: int = 1) -> inspect.Traceback:
Expand Down
2 changes: 2 additions & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Pending
* Fixed template panel to avoid evaluating ``LazyObject`` when not already
evaluated.
* Added support for Django 5.0.
* Refactor the ``utils.get_name_from_obj`` to simulate the behavior of
``django.contrib.admindocs.utils.get_view_name``.

4.2.0 (2023-08-10)
------------------
Expand Down
12 changes: 9 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,24 @@ def x():
return 1

res = get_name_from_obj(x)
self.assertEqual(res, "tests.test_utils.x")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_func.<locals>.x"
)

def test_lambda(self):
res = get_name_from_obj(lambda: 1)
self.assertEqual(res, "tests.test_utils.<lambda>")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_lambda.<locals>.<lambda>"
)

def test_class(self):
class A:
pass

res = get_name_from_obj(A)
self.assertEqual(res, "tests.test_utils.A")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_class.<locals>.A"
)


class RenderStacktraceTestCase(unittest.TestCase):
Expand Down