Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom filter to parse default value from dict to json #801

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions service_catalog/models/tower_survey_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from django.forms import SelectMultiple as FormsSelectMultiple
from django.forms import TextInput as FormsTextInput
from django.forms import Textarea as FormsTextarea
from jinja2 import Template
from jinja2 import Template, Environment
from jinja2.exceptions import UndefinedError
from rest_framework.serializers import CharField as DjangoRestCharField
from rest_framework.serializers import ChoiceField as DjangoRestChoiceField
Expand All @@ -27,9 +27,21 @@
from Squest.utils.squest_model import SquestModel
from resource_tracker_v2.models import AttributeDefinition
from service_catalog.models import Operation
import json

logger = logging.getLogger(__name__)

custom_filters = {
"to_json": lambda value: json.dumps(value, indent=2), # Convert to JSON
}

# Initialize Jinja2 environment
custom_env = Environment()

# Dynamically add filters
for filter_name, filter_func in custom_filters.items():
custom_env.filters[filter_name] = filter_func


def get_choices_as_tuples_list(choices, default=None):
if default is None:
Expand Down Expand Up @@ -83,7 +95,9 @@ def templating_default(self, instance, user):
default_value = self.field_options.get('default')
if self.default is None:
return default_value
template = Template(self.default)

# Use the custom environment to create a Template
template = custom_env.from_string(self.default)
from service_catalog.api.serializers import InstanceSerializer
from profiles.api.serializers import UserSerializer
context = {
Expand Down
Loading