【发布时间】:2012-03-24 20:48:38
【问题描述】:
Here they say it's not supported out of the box.
您知道一种使 HTML 输入表单字段使用 WTForms 的“只读”属性的方法吗?
【问题讨论】:
标签: python html forms wtforms readonly-attribute
Here they say it's not supported out of the box.
您知道一种使 HTML 输入表单字段使用 WTForms 的“只读”属性的方法吗?
【问题讨论】:
标签: python html forms wtforms readonly-attribute
解决方案是在表单字段声明中使用render_kw。
my_field = fields.StringField('Label', render_kw={'readonly': True})
【讨论】:
我假设您在谈论 HTML/XHTML 中的 <input readonly> 属性,这不是您链接的讨论线程的内容。 (链接的线程是关于如何忽略传递的表单输入的低级问题)
设置只读属性(实际上是字段上的任何属性)的方法是作为模板中的关键字参数。如果使用 Jinja,这看起来像 (html5):
{{ form.myfield(readonly=true) }}
对于 XHTML 或早于 0.6.3 的 WTForms 版本:
{{ form.myfield(readonly="readonly") }}
请注意,'readonly' 属性只是对浏览器的提示,它对用户提交的内容没有影响。这就是说,恶意用户(或使用带有自定义 JS 的浏览器的人,例如 lagreasemonkey 或 JS 控制台或 DOM 树)可以生成 POST 请求来更改字段的值,而不管是否设置了 readonly 属性输入标签。
因此,readonly 属性仅可用作修改用户体验的选项(例如,使用 JS 禁用基于某些事件/动作的字段)并且来自“只读”字段的输入不再可用比任何其他表单输入都值得信赖。
【讨论】:
render_kw={'readonly': True} 以只读应用。 (仅添加此评论,因为您的评论得到了很多提升)。
https://wtforms-components.readthedocs.org/en/latest/#
from wtforms import Form, DateField, TextField
from wtforms_components import TimeField, read_only
class EventForm(Form):
name = TextField('Name')
start_date = DateField('Start date')
start_time = TimeField('Start time')
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
read_only(self.name)
【讨论】:
另一种可能是使用隐藏字段,然后在您的视图中,您可以打印出{{ form.field.data }} 以显示为文本。
【讨论】: