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

This commit is contained in:
Jeremy Stretch 2023-08-09 14:39:02 -04:00
parent 93f6574902
commit 2d3d8850c2

View File

@ -257,14 +257,19 @@ class ConfigTemplate(SyncedDataMixin, ExportTemplatesMixin, TagsMixin, ChangeLog
""" """
Render the contents of the template. Render the contents of the template.
""" """
context = context or {} _context = dict()
app_ns = registry['model_features']['custom_fields'].keys() # Populate the default template context with NetBox model classes, namespaced by app
for app in app_ns: # TODO: Devise a canonical mechanism for identifying the models to include (see #13427)
context.setdefault(app, {}) for app, model_names in registry['model_features']['custom_fields'].items():
models = apps.get_app_config(app).get_models() _context.setdefault(app, {})
for model in models: for model_name in model_names:
context[app][model.__name__] = model 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 # Initialize the Jinja2 environment and instantiate the Template
environment = self._get_environment() environment = self._get_environment()
@ -272,7 +277,7 @@ class ConfigTemplate(SyncedDataMixin, ExportTemplatesMixin, TagsMixin, ChangeLog
template = environment.get_template(self.data_file.path) template = environment.get_template(self.data_file.path)
else: else:
template = environment.from_string(self.template_code) template = environment.from_string(self.template_code)
output = template.render(**context) output = template.render(**_context)
# Replace CRLF-style line terminators # Replace CRLF-style line terminators
return output.replace('\r\n', '\n') return output.replace('\r\n', '\n')