From 8b01c30c51a623f23d12cffea51d8f5805cdeba0 Mon Sep 17 00:00:00 2001 From: Abhimanyu Saharan Date: Thu, 10 Aug 2023 00:27:59 +0530 Subject: [PATCH] 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 --- netbox/extras/models/configs.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/netbox/extras/models/configs.py b/netbox/extras/models/configs.py index 6bd6019b9..47e8dcd82 100644 --- a/netbox/extras/models/configs.py +++ b/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')