Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to Render Bound Django Form Which Has Arbitrary Text & HTML Injected, as HTML-Safe in the Template?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 462
    Answer it

    I am trying to return a bound form that has been modified and has some arbitrary text and HTML inserted into it. I have done some research and have been able to successfully insert some arbitrary text into a bound form but I haven't found any way to render the injected HTML as HTML. It renders as plain text. How can I achieve my goal?


    Here is my code:


    def multi_text(request):
        if request.method == 'POST':
            data = request.POST.copy()
            form = MultilineForm(data=data)
            if form.is_valid():
                cd = form.cleaned_data
      ['text'] = '<i>Hello hello</i>'
                return render(request, 'multi_text.html', {'form': form})
            form = MultilineForm()
        return render(request, 'multi_text.html', {'form': form})
    class MultilineForm(ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['text'].widget.attrs.update({'class': 'form-control'}, verbose_name='Text', placeholder='Type your text here...')
  ['text'] = '...'
        class Meta:
            model = Multiline
            fields = ['text']
            widgets = {
                'text': Textarea(attrs={}),
    # template.html
    <form method="post" action="" class="form">
            {% csrf_token %}
            {{ form.text.as_widget }}
            <span class="input-group-btn">
            <input type="submit" value="Check" class="form-control btn btn-primary">





 0 Answer(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: