django 在渲染表单时转义小部件

发布于 2024-10-16 18:56:06 字数 642 浏览 3 评论 0原文

我创建了一个自定义小部件以及一个使用它的表单。 以前,我在调试时只有一个简单的模板来显示表单:

<form>
    {{ run_form.as_p }}
</form>

现在我想将每个表单字段包含在 div 中,所以我将模板更改为

{% for field in form %}
      <div class="fieldWrapper">
           {{ field.errors }}
           {{ field.label_tag }}: {{ field }}
      </div>
{% endfor %}

但现在看来,当我的字段渲染时,所有它的字符是 html 转义的,所以现在当我查看它的源代码时,它看起来像 &lt;input type=&quot;text&quot; id="id_scriptscrap"/> 它应该在的地方

我有什么遗漏的吗?为什么第一个模板会在不转义的情况下输出它,而第二个模板会转义?也许我在创建自定义小部件类时做错了什么?

I created a custom widget, and a form that uses it.
Previously, I just had a simple template to show the form when I was debugging it:

<form>
    {{ run_form.as_p }}
</form>

Now I want to enclose each form field in a div, so I've changed the template to

{% for field in form %}
      <div class="fieldWrapper">
           {{ field.errors }}
           {{ field.label_tag }}: {{ field }}
      </div>
{% endfor %}

But now it seems that when my field is rendered, all it's characters are html-escaped, so now when I look at it's source code, it looks something like <input type="text" id="id_scriptscrap"/> where it should've been
<input type="text" id="id_scriptscrap"/>.

Is there something I'm missing? Why would the first template output it without escaping, while the second does escape? Perhaps I did something wrong when creating the custom widget class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

糖果控 2024-10-23 18:56:06

也许我在创建自定义小部件类时做错了什么?

可能吧,尽管由于您没有发布代码而无法判断。

form.as_p 起作用的原因是 form._html_output() 方法(这是各种 as_foo 方法使用的方法)调用 mark_safe 在其输出上。但是,每个内置小部件类在自己的输出上调用mark_safe,这就是它们单独工作的原因。您可能只需要在自定义小部件上执行相同的操作即可。

Perhaps I did something wrong when creating the custom widget class?

Probably, although it's impossible to tell since you don't post the code.

The reason why form.as_p works is that the form._html_output() method - which is what the various as_foo methods use - calls mark_safe on its output. However, each of the built-in widget classes also call mark_safe on their own output, which is why they work individually. You probably just need to do the same on your custom widget.

万水千山粽是情ミ 2024-10-23 18:56:06

其他原因:如果您不小心使用小部件而不是字段定义表单(例如 password = forms.PasswordInput 而不是 password = forms.CharField(widget=forms.PasswordInput)< /代码>

Alternate cause: this also happens if you accidentally defined your form with widgets instead of fields (for example password = forms.PasswordInput instead of password = forms.CharField(widget=forms.PasswordInput)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文