Bladeren bron

Exposes all models in device context data (#13389)

* exposes all models in device context data #12814

* added app namespaces to the context data

* revert object to device in context data

* moved context to render method of ConfigTemplate

* removed print

* Include only registered models; permit passed context data to overwrite apps

---------

Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
Abhimanyu Saharan 2 jaren geleden
bovenliggende
commit
8b01c30c51
1 gewijzigde bestanden met toevoegingen van 16 en 2 verwijderingen
  1. 16 2
      netbox/extras/models/configs.py

+ 16 - 2
netbox/extras/models/configs.py

@@ -1,3 +1,4 @@
+from django.apps import apps
 from django.conf import settings
 from django.core.validators import ValidationError
 from django.db import models
@@ -8,6 +9,7 @@ from jinja2.sandbox import SandboxedEnvironment
 
 from extras.querysets import ConfigContextQuerySet
 from netbox.config import get_config
+from netbox.registry import registry
 from netbox.models import ChangeLoggedModel
 from netbox.models.features import CloningMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin
 from utilities.jinja2 import ConfigTemplateLoader
@@ -255,7 +257,19 @@ class ConfigTemplate(SyncedDataMixin, ExportTemplatesMixin, TagsMixin, ChangeLog
         """
         Render the contents of the template.
         """
-        context = context or {}
+        _context = dict()
+
+        # Populate the default template context with NetBox model classes, namespaced by app
+        # TODO: Devise a canonical mechanism for identifying the models to include (see #13427)
+        for app, model_names in registry['model_features']['custom_fields'].items():
+            _context.setdefault(app, {})
+            for model_name in model_names:
+                model = apps.get_registered_model(app, model_name)
+                _context[app][model.__name__] = model
+
+        # Add the provided context data, if any
+        if context is not None:
+            _context.update(context)
 
         # Initialize the Jinja2 environment and instantiate the Template
         environment = self._get_environment()
@@ -263,7 +277,7 @@ class ConfigTemplate(SyncedDataMixin, ExportTemplatesMixin, TagsMixin, ChangeLog
             template = environment.get_template(self.data_file.path)
         else:
             template = environment.from_string(self.template_code)
-        output = template.render(**context)
+        output = template.render(**_context)
 
         # Replace CRLF-style line terminators
         return output.replace('\r\n', '\n')