更改Django表单中帮助文本的全局行为

4

我希望利用Django中的默认帮助文本,但我不喜欢它的处理方式。我想要如下:

<tr><label>djangolab</label><input>djangoinput</input><span>djangohelp></span><span class='onhovershowhelp'>?</span>

默认情况下不提供最后一个元素。当鼠标悬停在“?”上时,CSS会将帮助文本span的可见性从隐藏更改为可见。
我希望所有模型表单都能直接显示 '{{form}}',因此我希望全局设置:
  1. 默认情况下带有一些属性(z=1, hidden)的帮助文本span
  2. 在表单行中添加另一个span。
我不想为每个模型表单/字段等做这个操作,使用模板中的循环并手动构建它等...

你想为一个字段在所有表单中使用同一份帮助文本吗? - Arpit Solanki
@ArpitSolanki 再次你好!不,我想保留django已经提供的所有默认文本,就像它原本的样子一样。我只是想稍微改变一下渲染器。我认为也许在一个通用的ModelForm类中覆盖'to_table'方法是正确的方式,因为我所有的模型都继承自这个类,我正在开始研究这个问题 - 但如果有人发现更好/更好的解决方案,我会很高兴看到它。 - kabanus
不是很确定,但您可以在表单中创建一个init函数,然后调用super,然后可以像这样更新属性:self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'}) - Arpit Solanki
1个回答

4

明白了。让所有表单都继承这样的东西(_html_output 调用是直接从 Django 源代码中获取的隐藏实现细节):

import django.forms

class GenericForm(django.forms.ModelForm):
    def as_table(self):
        return self._html_output(
            normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
            error_row='<tr><td colspan="2">%s</td></tr>',
            row_ender='</td></tr>',
            help_text_html='<a class="helptext">?<span>%s</span></a>',
            errors_on_separate_row=False)
        return html

以下是相关的CSS代码:

.helptext {
    margin: 5px;
    color: blue;
}

a.helptext span {
    display:none;
    width: 30em;
    text-align: justify;
    z-index:1;
}

a.helptext:hover span {
    display:inline;
    position:absolute;
    background:#ffffff;
    border:1px solid #cccccc;
    color:#6c6c6c;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接