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.
- [Django]-Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries
- [Django]-Django no such table:
- [Django]-Additional field while serializing django rest framework
4
You can use an external file to increase maintainability and separation of concern:
- modify yourform’s
__init__()
method ; - after the
super(MyForm, self).__init__(*args, **kwargs)
; - assign the result of
render_to_string()
toself.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>
- [Django]-How can I check if a Python unicode string contains non-Western letters?
- [Django]-Gunicorn, no module named 'myproject
- [Django]-Django edit form based on add form?
- [Django]-Use Django ORM as standalone
- [Django]-Django prefetch_related with limit
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
Source:stackexchange.com