WTF or WTForms
I'm trying to integrate Flask as the backend for the UI I'm working with.
Unfortunately the UI already has the CSS and JavaScript set up for the forms (to accommodate for the UI but also for older versions of IE and other cases).
The first problem that I'm running into is that there is already a label for the fields. If I use the .labels attribute in the template:
{{ form.username.label }}
then it creates an extra label which I can't seem to add any attributes to for the CSS/JavaScript. However if I leave the .label attribute off then it creates an extra blank text field above the username input.
The code in my forms.py file is:
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
Am I missing something on this?
The second part is adding attributes to the form itself. I've found how to add the HTML class attribute using class_='classname' , but the Flask-WTF and WTForms documentation don't seem to touch on any other attributes (such as autcomplete="off" or placholder="username" )
Is there some way to accomplish this with Flask-WTF or WTForms that I'm just missing? Am I limited to manual attributes and/or Jinja macros for this type of functionality? I can't imagine this is something that would be missing form WTForms and Flask-WTF but I also don't see it mentioned anywhere in the docs or on Google/StackOverflow.
Thanks!
After happening on this WTForms : How to add "autofocus" attribute to a StringField I tried to use the same approach to my problem. And it worked. Still not sure why this isn't covered in the WTForms or Flask-WTForms docs.
So for the labels, to have them contain the class, or other attributes you require, in the template add it the same as the class_= explanation above.
So in this case :
{{ form.username.label(class_="ie9") }}
adds the appropriate class to the label when rendered.
For the string inputs the attributes are again added in the template:
{{ form.username(class_="formplace", placeholder="Username", autocomplete="off", autofocus="true", size=32) }}
Renders with the proper HTML for class, placeholder, autocomplete, autofocus, and size in the field.
I'm sure this can be made dynamic and reusable, but just wanted to show the solution since I can't be the only person having this issue. Specifically it was 0xTim's solution that lead me to something usable.
链接地址: http://www.djcxy.com/p/61768.html下一篇: WTF或WTForms