简体   繁体   中英

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?

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>

使用具有只读的textarea标签

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM