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?
Common Fields These built-in widgets represent HTML elements. CharField() is a Django form field that takes in a text input. It has the default widget TextInput, the equivalent of rendering the HTML code <input type="text" ...> . This field works well for collecting one line inputs such as name or address.
help_text attribute is used to display the “help” text along with the field in form in admin interface or ModelForm. It's useful for documentation even if your field isn't used on a form. For example, you can define the pattern of date to be taken as input in the help_text of DateField.
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With