Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms support for input readonly attribute?

Tags:

Here they say it's not supported out of the box.

Do you know a way to make HTML input form fields use the 'readonly' attribute with WTForms?

like image 367
casual Avatar asked Mar 07 '12 10:03

casual


People also ask

Can I use input readonly?

Definition and Usage The readonly attribute is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

How do you add a readonly attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.

What is a readonly attribute?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.

What is the use of readonly element in JavaScript?

Definition and Usage The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.


2 Answers

The solution is using render_kw in form field declaration.

my_field = fields.StringField('Label', render_kw={'readonly': True}) 
like image 191
Bruno Rocha - rochacbruno Avatar answered Sep 17 '22 21:09

Bruno Rocha - rochacbruno


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.

like image 44
Crast Avatar answered Sep 19 '22 21:09

Crast