Use Template.render(context) as initial forms.HiddenInput value

My goal is to use the rendered out template as the initial value of the HiddenInput field. But as the out rendered contains characters like " this then creates a problem when the form field is rendered out.

This is already a problem with a simple template like <body style="box-sizing: border-box; margin: 0;"></body>
Which then creates a form like this:

<form role="form" method="post" style="margin: 0;">
            <input type="hidden" name="csrfmiddlewaretoken" value="ZsORB2ibL6YfVWG2oY6TkhwXRThQSE0CSXEpiVgpZiCU9DfDRQEHmw56dWANQJLi">
            <input type="hidden" name="template" value="<body style=" box-sizing:="" border-box;="" margin:="" 0;"="">" id="id_template"&gt;
        </form>

As can be observer the id="id_template"&gt is outside of the input value section.

The form is just created like this:

class TemplateModelForm(ModelForm):
    class Meta:
        model = Template
        fields = ("template",)
        widgets = {"template": forms.HiddenInput()}

    def __init__(self, *args, **kwargs):
        self.page_view_context = kwargs.pop("page_view_context", None)
        super().__init__(*args, **kwargs)
        template = get_template(self.instance.name)
        self.initial["template"] = template.render(self.page_view_context)

I have tried to use mark_safe and force_str on the rendered content but it didn’t help.

Any suggestion on what I could do to solve this issue? I also know that this is probably not a very common issue :sweat_smile:

I don’t quite follow what you’re trying to accomplish here - I certainly wouldn’t want to send anything out to the user that can’t be validated and verified when it’s sent back in - it’s too easy for the user to modify it.

Given that you don’t know what’s going to be rendered, I don’t think there is a guaranteed way to ensure it’s safe. (Mark_safe is going in the opposite direction - you definitely don’t want to do that.)

I’d probably either stash the rendered template into session (most likely), or do something like base64 encode the rendered text if the client actually needed to see that hidden field.

Thanks for the encoding idea seams like it will work