Daniel Quinn
Daniel Quinn

Reputation: 6408

How to add an HTML class to a Django form's help_text?

I have a simple form

class MyForm(forms.Form):
    ...
    fieldname = forms.CharField(help_text="Some help text")

I can then display this form with django's handy {{ form.as_ul }} if I like, now I need to stylise the help_text and I have no idea how. Django doesn't appear to wrap that string in anything that will let my CSS get to it so at the moment, I've restored to:

class MyForm(forms.Form):
    ...
    fieldname = forms.CharField(help_text='<div class="helptext">Some help text</div>')

Which I know is wrong so I'm looking here for better advice.

Upvotes: 10

Views: 6363

Answers (4)

anjanesh
anjanesh

Reputation: 4251

I don't know since this was available but this works for me in the template :

{{ field|add_label_class:'class-name' }}

Upvotes: 0

Alexander Lebedev
Alexander Lebedev

Reputation: 6044

There's only that much you can customize in UI from form options. The more flexible way to approach a problem is to create your own form template then and reuse it instead of {{ form.as_something }}. Read these topics from Django documentation:

This worked very well when I needed significantly customized form marks yet keeping it DRY.

Upvotes: 7

bjw
bjw

Reputation: 2017

A more convenient way to do this is to:

from django.utils.safestring import mark_safe

and then:

field = models.TextField(help_text=mark_safe("some<br>html"))

Upvotes: 14

Felix Kling
Felix Kling

Reputation: 816404

I guess there is no other way, otherwise there probably wouldn't be a need for this ticket: http://code.djangoproject.com/ticket/8426.

You could apply the patch that is provided there.

Upvotes: 2

Related Questions