5

I want to show the model field help_text as an HTML title attribute in a form, instead of it being appended to the end of the line, as is the default.

I like all the information about a model Field being in one place (in the Model definition itself), and would therefore not like to specify a custom title for each widget. It is okay, however, if there is a way to specify that the title attribute of each of widgets should be equal to the value of help_text. Is that possible? I'm looking for something to the effect of:

widgets = {'url':TextInput(attrs={'title': help_text})}

The only other way I can think of doing this, is to make custom widgets for every single one of the built-in Widget types. Is there an easier, lazier way to achieve the same effect?

Using Javascript is also an option, but that would really only be a very far-off last resort. I'm thinking that this has to be a rather common use-case; how have you guys handled it in the past?

Herman Schaaf
  • 46,821
  • 21
  • 100
  • 139

2 Answers2

3
Model._meta.get_field('field').help_text

In your case

widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}
errx
  • 1,761
  • 4
  • 18
  • 25
  • Neat, I didn't know that. How about hiding the `help_text` so that it's only displayed in the title? – Herman Schaaf Jan 22 '11 at 21:27
  • You want to hide it in a form? just make your own custom form http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template – errx Jan 22 '11 at 21:33
  • Yeah, you're right. Just looping over the form's fields would do the trick. Thanks! – Herman Schaaf Jan 22 '11 at 21:37
  • 1
    Just for future reference, I made a post of how I made it all work together in the end, http://www.ironzebra.com/news/10 . There are some other interesting facets to the problem as well. – Herman Schaaf Jan 22 '11 at 23:05
3

Here's another way using a class decorator.

def putHelpTextInTitle (cls):
    init = cls.__init__

    def __init__ (self, *args, **kwargs):
        init(self, *args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['title'] = field.help_text

    cls.__init__ = __init__
    return cls

@putHelpTextInTitle
class MyForm (models.Form):
    #fields here

The class decorator is adapted from here

Community
  • 1
  • 1
aptwebapps
  • 1,866
  • 1
  • 13
  • 17
  • 1
    Nice. Add `field.help_text = None` at the end of the `for` loop to avoid Django showing the `help_text` twice. – SaeX Mar 27 '15 at 17:36