开发者

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 thi开发者_运维百科nk 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?


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

In your case

widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜