【问题标题】:How do I input HTML into the help text of a Django form field?如何将 HTML 输入到 Django 表单字段的帮助文本中?
【发布时间】:2012-05-29 04:41:57
【问题描述】:

我尝试在我的 Django 表单中为选择字段生成帮助文本

i_agree = forms.CharField(label="", help_text="Initial to affirm that you agree to the <a href='/contract.pdf'>contract</a>.", required=True, max_length="4")

但是,原始 HTML 在帮助文本中呈现为输出。如何将 HTML 输入到 Django 表单字段的帮助文本中?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您可以在模型中使用mark_safe 来指示该html 是安全的,并且应该这样解释:

    from django.utils.safestring import mark_safe
    
    i_agree = forms.CharField(label="", help_text=mark_safe("Initial to affirm that you agree to the <a href='/contract.pdf'>contract</a>."), required=True, max_length="4")
    

    【讨论】:

    • 您也可以将其直接应用于该字段的help_textself.fields['i_agree'].help_text = mark_safe("Initial to affirm that you agree to the &lt;a href='/contract.pdf'&gt;contract&lt;/a&gt;.")
    【解决方案2】:

    如果您自己循环表单,您也可以在模板中将其标记为安全:

    {% for f in form %}
        {{f.label}}{{f}}{{f.help_text|safe}}    
    {%endfor%}
    

    这是在模板中这样做的一个非常简单的示例。你需要做更多的事情才能让它看起来不错。

    【讨论】:

    • 这是一个很好的解决方案,但它不适用于form.as_[p,ul,table] 的自动输出。
    【解决方案3】:

    您可以使用外部文件来提高可维护性和关注点分离:

    1. 修改表单的__init__() 方法;
    2. super(MyForm, self).__init__(*args, **kwargs)之后;
    3. render_to_string()的结果赋值给self.fields['my_field'].help_text

    forms.py

    从 django.template.loader 导入 render_to_string

    class MyForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            # Only in case we build the form from an instance,
            if 'instance' in kwargs and kwargs['instance'].nature == consts.RiskNature.RPS:
                self.fields['my_field'].help_text = render_to_string('components/my-template.html')
                #                      ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 
    

    我的模板.html

    {% load i18n %}
    <table class="table table-bordered">
        <tr>
            <th>{% trans 'Externe' %}</th>
        </tr>
        <tbody class="text-muted">
            <tr>
                  <td>{% trans "En lien avec les relations de travail" %}</td>
              </tr>
              <tr>
                  <td>{% trans "-" %}</td>
              </tr>
        </tbody>
    </table>
    

    【讨论】:

    • 秋千和环形交叉路口 - 是的,将 HTML 保存在外部文件中很好,但被覆盖的保存方法最终可能会充满不相关的功能 - 而且你已经将 help_text 设置在你不希望的地方看。你能把 render_to_string 直接放在字段定义本身上吗?
    【解决方案4】:

    使用带有只读的 textarea 标签

    <textarea readonly> <p>stuff</p> </textarea>
    

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2012-07-13
      • 2017-11-11
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2020-06-28
      • 2018-11-22
      • 2011-02-23
      相关资源
      最近更新 更多