WTForms support for input readonly attribute?

家住魔仙堡 提交于 2019-11-28 23:17:29

I assume you are talking about the <input readonly> attribute in HTML/XHTML, which is not what that discussion thread you linked is about. (the linked thread is about a lower-level issue with how to ignore passed form input)

The way to set a readonly attribute (and indeed any attribute on a field) is as a keyword-arg in your template. If using Jinja, this looks like (html5):

{{ form.myfield(readonly=true) }}

And for XHTML or versions of WTForms older than 0.6.3:

{{ form.myfield(readonly="readonly") }}

Just note that the 'readonly' attribute is only a hint to the browser, and it has no impact on what the user submits. This is to say, a malicious user (or someone using a browser with custom JS a la greasemonkey or a JS console or a DOM tree) could generate a POST request changing the value of a field regardless of whether the readonly attribute is set on the input tag.

For this reason, the readonly attribute is only useful as an option to modify the user experience (for example, disabling a field based on some event/action using JS) and the input coming from a 'readonly' field is no more trust-able than any other form input.

The solution is using render_kw in form field declaration.

my_field = fields.StringField('Label', render_kw={'readonly': True})
0xd3

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)
Scott

Another possibility is to use a hidden field, and then in your view, you can print out {{ form.field.data }} to display as text.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!