Can I show model help text as a title attribute for forms in Django?

I want to show the model field help_textas an HTML attribute titleon the form, and not be added to the end of the line, as by default.

I like all the information about the model field in one place (in the model definition itself), and therefore I would not want to specify a custom one titlefor each widget. This is normal, however, if there is a way to indicate that the title attribute of each of the widgets should be equal to the value help_text. Is it possible? I was looking for something for the effect:

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

The only way I can do this is to create custom widgets for each of the widget's built-in types. Is there an easier, lazy way to achieve the same effect?

Using Javascript is also an option, but it really will be a very distant last resort. I think this should be a fairly common use case; how did you guys deal with him in the past?

+5
source share
2 answers
Model._meta.get_field('field').help_text

In your case

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

Here's another way to use 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

Class decorator adapted from here

+2
source

All Articles