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
    • 494
    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
                form.data['text'] = '<i>Hello hello</i>'
                return render(request, 'multi_text.html', {'form': form})
        else:
            form = MultilineForm()
        return render(request, 'multi_text.html', {'form': form})
    
    # forms.py
    
    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...')
            self.data['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">
            </span>         
        </form>

    ```

     

     

     

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: