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.
我想将模型字段help_text显示为表单中的HTML标题属性,而不是将其作为默认值附加到行的末尾。
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:
我喜欢模型字段在一个地方(在模型定义本身中)的所有信息,因此不想为每个小部件指定自定义标题。但是,如果有一种方法可以指定每个小部件的title属性应该等于help_text的值,那也没关系。那可能吗?我正在寻找一些效果:
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?
我能想到的另一种方法是为内置的Widget类型中的每一个创建自定义小部件。是否有更简单,更懒惰的方式来达到同样的效果?
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?
使用Javascript也是一种选择,但这实际上只是一个非常遥远的最后手段。我认为这必须是一个相当普遍的用例;你们过去怎么处理它?
2 个解决方案
#1
3
Model._meta.get_field('field').help_text
In your case
在你的情况下
widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}
#2
2
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
类装饰器从这里改编而来
#1
3
Model._meta.get_field('field').help_text
In your case
在你的情况下
widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}
#2
2
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
类装饰器从这里改编而来