Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to show model help text as a title attribute on forms in Django?

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?

like image 875
Herman Schaaf Avatar asked Jan 22 '11 21:01

Herman Schaaf


2 Answers

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

In your case

widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}
like image 75
errx Avatar answered Nov 16 '22 07:11

errx


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

like image 44
aptwebapps Avatar answered Nov 16 '22 05:11

aptwebapps