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

65👍

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")

13👍

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.

4👍

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>

-6👍

Use a textarea tag with readonly

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

Leave a comment