【问题标题】:Change behaviour of help text in django form globally全局更改 django 形式的帮助文本的行为
【发布时间】:2017-06-21 14:39:17
【问题描述】:

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

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

默认情况下不提供最后一个元素。悬停在“?”上的 CSS将帮助文本范​​围的可见性从隐藏更改为可见。

我希望事情开箱即用,因此“{{form}}”将按照我对任何模型表单的需要显示。所以我想要全局:

  1. 帮助文本默认跨越一些属性(z=1,隐藏)
  2. 添加另一个跨度以形成行。

我不想为每个模型表单/字段等执行此操作,请在模板中使用循环并手动构建此等...

【问题讨论】:

  • 您想要一个字段的所有表单中的单个帮助文本吗?
  • @ArpitSolanki 再次嗨!不,我想保留 django 已经提供的所有默认文本,原样保留。我只是想稍微改变一下渲染器。我认为也许在我的所有模型继承的通用 ModelForm 类中覆盖“to_table”是可行的方法,我将开始着手解决这个问题 - 但如果有人找到更好/更好的解决方案,我会很高兴看到它.
  • 不完全确定,但您可以在表单中创建一个 init 函数,然后调用 super ,然后您可以更新这样的属性 self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

标签: django


【解决方案1】:

知道了。让所有表单都继承这样的东西(_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;
}

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2016-07-29
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2022-07-08
    • 2018-07-30
    相关资源
    最近更新 更多