From c0825fff08e4da8153df13eafa2b13d34af5f74e Mon Sep 17 00:00:00 2001 From: DIFEZI Tchakoli Chissou Date: Sat, 13 Jul 2024 18:23:00 +0000 Subject: [PATCH] Avoid adding the same items multiple times into the same menu [21](https://github.com/LaLogiaDePython/django-menu-generator/pull/21) --- menu_generator/templatetags/menu_generator.py | 4 +++- menu_generator/tests/test_menu.py | 12 +++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/menu_generator/templatetags/menu_generator.py b/menu_generator/templatetags/menu_generator.py index 9752939..52d46ea 100755 --- a/menu_generator/templatetags/menu_generator.py +++ b/menu_generator/templatetags/menu_generator.py @@ -20,7 +20,9 @@ def get_menu(context, menu_name): :param menu_name: String, name of the menu to be found :return: Generated menu """ - menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) + # Instantiate a new list() or else the same instance of the menu_list gets used over and over + # (and possibly re-adding the menu_from_apps list on each request) + menu_list = list(getattr(settings, menu_name, defaults.MENU_NOT_FOUND)) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: diff --git a/menu_generator/tests/test_menu.py b/menu_generator/tests/test_menu.py index 6bdd66d..bbfb897 100755 --- a/menu_generator/tests/test_menu.py +++ b/menu_generator/tests/test_menu.py @@ -351,4 +351,14 @@ def test_generate_menu_selected_related_views_submenu(self): self.assertEqual(len(nav), 1) self.assertEqual(nav[0]["selected"], True) self.assertEqual(nav[0]["submenu"][0]["selected"], True) - self.assertEqual(nav[0]["submenu"][1]["selected"], False) \ No newline at end of file + self.assertEqual(nav[0]["submenu"][1]["selected"], False) + + def test_subsequent_requests(self): + self.request.user = TestUser(authenticated=True) + ctx = { + 'request': self.request + } + nav1 = get_menu(ctx, 'NAV_MENU') + nav2 = get_menu(ctx, 'NAV_MENU') + # Both menus should be equal + self.assertEqual(nav1, nav2)