Forráskód Böngészése

Closes #23739: Fix custom links in restricted exports

Custom link columns were left empty when a table was exported in
restricted mode, as the export has no template context from which to
take the user's request. Use the request the table was configured for
instead. Records beyond the current page are also now serialized in
chunks, rather than reloading the page along with each one.

Legacy mode also uses this request, so custom links in exports now
receive request and perms, as they do in the list view.
Jeremy Stretch 5 órája
szülő
commit
9c87a5eaf9

+ 25 - 0
netbox/extras/tests/test_templatetags.py

@@ -1,9 +1,12 @@
+import csv
+import io
 from unittest.mock import patch
 
 from django.contrib.auth import get_user_model
 from django.contrib.auth.context_processors import PermWrapper
 from django.contrib.auth.models import AnonymousUser
 from django.test import RequestFactory, TestCase, override_settings
+from django.urls import reverse
 from django.utils.html import escape
 
 from core.models import ObjectType
@@ -362,6 +365,28 @@ class CustomLinkRestrictedRenderingTest(TestCase):
         # A table built from a list is also serialized in chunks
         self.assertEqual([len(call.args[1]) for call in load_objects.call_args_list], [2, 1])
 
+    @patch('netbox.tables.columns.TEMPLATE_OBJECTS_CHUNK_SIZE', 2)
+    def test_table_export_view(self):
+        custom_link = CustomLink.objects.create(
+            name='Link 1', enabled=True, link_text='x', link_url='/{{ object.slug }}'
+        )
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        # Enough sites that the last page doesn't absorb the others as orphans
+        Site.objects.bulk_create([Site(name=f'Site {i}', slug=f'site-{i}') for i in range(4, 10)])
+        self.client.force_login(self.user)
+
+        # Export all sites, beyond the first page of the table
+        with patch('utilities.template_objects._load_objects', wraps=_load_objects) as load_objects:
+            response = self.client.get(reverse('dcim:site_list'), {
+                'export': '', 'export_format': 'csv', 'per_page': 1,
+            })
+            content = b''.join(response.streaming_content) if response.streaming else response.content
+        self.assertEqual(response.status_code, 200)
+        rows = csv.DictReader(io.StringIO(content.decode('utf-8-sig')))
+        self.assertEqual([row['Link 1'] for row in rows], [f'/site-{i}' for i in range(1, 10)])
+        # The page is serialized at once, and the records following it in chunks
+        self.assertEqual([len(call.args[1]) for call in load_objects.call_args_list], [1, 2, 2, 2, 2])
+
     @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
     def test_table_anonymous_user(self):
         custom_link = CustomLink.objects.create(

+ 8 - 8
netbox/netbox/tables/columns.py

@@ -721,7 +721,9 @@ class CustomLinkColumn(tables.Column):
         super().__init__(*args, **kwargs)
 
     def _render_customlink(self, record, table):
-        request = getattr(table, 'context', {}).get('request')
+        # A table rendered in a template has a context, while one being exported has only the request it was
+        # configured for
+        request = getattr(table, 'context', {}).get('request') or getattr(table, 'request', None)
         # Share the render state, and the objects serialized for it, among all of the table's custom link columns.
         # Retain them only for the request they were created for.
         cached_request, state, objects = getattr(table, '_custom_link_render_state', (None, None, None))
@@ -750,16 +752,14 @@ class CustomLinkColumn(tables.Column):
     def _get_template_object(record, table, state, objects):
         """
         Return the TemplateObject for a record, retaining the objects serialized in the given dict. The records on the
-        table's current page are serialized at once, or for an unpaginated table (e.g. an export), the records in
+        table's current page are serialized at once, or for a record not on it (e.g. in an export), the records in
         chunks following this one.
         """
         if record.pk not in objects:
-            if page := getattr(table, 'page', None):
-                pks = [row.record.pk for row in page.object_list]
-                if record.pk not in pks:
-                    pks.append(record.pk)
-            else:
-                # Retain only the current chunk of an unpaginated table, and the related objects fetched for it
+            page = getattr(table, 'page', None)
+            pks = [row.record.pk for row in page.object_list] if page else []
+            if record.pk not in pks:
+                # Retain only the current chunk of the table, and the related objects fetched for it
                 objects.clear()
                 state.cache.clear()
                 pks = CustomLinkColumn._get_chunk(record, table)