django 在渲染表单时转义小部件
我创建了一个自定义小部件以及一个使用它的表单。 以前,我在调试时只有一个简单的模板来显示表单:
<form>
{{ run_form.as_p }}
</form>
现在我想将每个表单字段包含在 div 中,所以我将模板更改为
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
但现在看来,当我的字段渲染时,所有它的字符是 html 转义的,所以现在当我查看它的源代码时,它看起来像 <input type="text" 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能吧,尽管由于您没有发布代码而无法判断。
form.as_p
起作用的原因是form._html_output()
方法(这是各种as_foo
方法使用的方法)调用mark_safe
在其输出上。但是,每个内置小部件类还在自己的输出上调用mark_safe
,这就是它们单独工作的原因。您可能只需要在自定义小部件上执行相同的操作即可。Probably, although it's impossible to tell since you don't post the code.
The reason why
form.as_p
works is that theform._html_output()
method - which is what the variousas_foo
methods use - callsmark_safe
on its output. However, each of the built-in widget classes also callmark_safe
on their own output, which is why they work individually. You probably just need to do the same on your custom widget.其他原因:如果您不小心使用小部件而不是字段定义表单(例如
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 ofpassword = forms.CharField(widget=forms.PasswordInput)