Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
dangerChihuahua007 Avatar asked May 22 '12 16:05

dangerChihuahua007


People also ask

Is a Django form field that takes in a text input?

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.

What is help text in Django?

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.

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


2 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") 
like image 89
Furbeenator Avatar answered Sep 19 '22 09:09

Furbeenator


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.

like image 21
Fernker Avatar answered Sep 20 '22 09:09

Fernker