How do I input HTML into the help text of a Django form field?

I tried to generate help text for a Choice Field in my Django form with

i_agree = forms.CharField(label="", help_text="Initial to affirm that you agree to the <a href='/contract.pdf'>contract</a>.", required=True, max_length="4")

However, the raw HTML is rendered as output in the help text. How do I input HTML into the help text of a Django form field?

Answers


You can use mark_safe in the model to indicate the html is safe and it should be interpreted as such:

from django.utils.safestring import mark_safe

i_agree = forms.CharField(label="", help_text=mark_safe("Initial to affirm that you agree to the <a href='/contract.pdf'>contract</a>."), required=True, max_length="4")

You can alternatively mark it as safe in the template if you loop through the form yourself:

{% for f in form %}
    {{f.label}}{{f}}{{f.help_text|safe}}    
{%endfor%}

That's a very simple example of doing so in the template. You would need to do more than that to make it look nice.


You can use an external file to increase maintainability and separation of concern:

  1. modify yourform's __init__() method ;
  2. after the super(MyForm, self).__init__(*args, **kwargs) ;
  3. assign the result of render_to_string() to self.fields['my_field'].help_text.
forms.py

from django.template.loader import render_to_string

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # Only in case we build the form from an instance,
        if 'instance' in kwargs and kwargs['instance'].nature == consts.RiskNature.RPS:
            self.fields['my_field'].help_text = render_to_string('components/my-template.html')
            #                      ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 
my-template.html
{% load i18n %}
<table class="table table-bordered">
    <tr>
        <th>{% trans 'Externe' %}</th>
    </tr>
    <tbody class="text-muted">
        <tr>
              <td>{% trans "En lien avec les relations de travail" %}</td>
          </tr>
          <tr>
              <td>{% trans "-" %}</td>
          </tr>
    </tbody>
</table>

Use a textarea tag with readonly

<textarea readonly> <p>stuff</p> </textarea>

Need Your Help

Performance Implications of Point-Free style

performance f# functional-programming pointfree

I’m taking my first baby-steps in learning functional programing using F# and I’ve just come across the Forward Pipe (|>) and Forward Composition (>>) operators. At first I thought they were just s...

How to apply two different styles to one element in android?

android xml android-layout inheritance styles

I have a TextView and I want to apply a Style which I use for all TextView elements plus another style which I only use within a specific Activity. Is there any possibility to do that?