Is there a way to implement Django templates in a form

I have a Django form where admins create user-specific pages, and I want admins to add {{username}} as input in the form so that when the content of the created page is rendered to a user the tag {{username}} becomes the username.

Here's what I have tried so far;

views.py:

class CreateCampaignView(LoginRequiredMixin, FormView):
    login_url = reverse_lazy('Portal:login')
    template_name = 'Portal/PostForm.html'
    form_class = PostForm
    success_url = reverse_lazy('Portal:feed')

    def form_valid(self, form, **kwargs):
        form.instance.Subject = form.cleaned_data['Subject']
        form.instance.Text_content = form.cleaned_data['Text_content']
        form.instance.HTML_content = form.cleaned_data['HTML_content']
        template = form.instance.HTML_content
        
        context = Context(dict({'username':'xxxx', 'email':'[email protected]'}))
        template.render(context)

        return super().form_valid(form, **kwargs)

This method is returning an error "str object does not have render", because HTML_content is a Text_filed in forms.py and I couldn't find a workaround to make this work.


You should create a Template for the data from the form, so:

from django.template import Template, Context

template = Template(form.cleaned_data['HTML_content'])
context = Context({'username': 'xxxx'}) # instead of xxxx, users.objects.filter(username='John')
rendered: str = template.render(context)