Using Flask-WTForms, how do I create a form section in html?

I read the extremely simplified Flask-WTF wiki and couldn't figure out what I could do with it. I get the impression that the <form> html section can now only look like

 <form method="post"> {{ form.hidden_tag() }} {{ form.name }} <input type="submit"> </form> 

But I really want to style my use, for example:

  <div class="row"> <div class="input-field col s6"> <i class="material-icons prefix">account_circle</i> <input value="FN" id="first_name" type="text" class="validate"> <label class="active" for="first_name">First Name</label> </div> <div class="input-field col s6"> <input value="LN" id="last_name" type="text" class="validate"> <label class="active" for="last_name">Last Name</label> </div> </div> 

Where can I fit {{ form.first_name }} and {{ form.last_name }} in?

EDIT: Let me tell you more about my answer: For example, I need something like Materialized datepicker (a good popup calendar that allows the user to select a date), it should be in <input class='datepicker' length="50"> . but now that I am replacing the whole <input> with {{ form.date }} ... I have lost this privilege to edit the class and what not.

+7
source share
2 answers

WTForms fields can be called with attributes that will be set on the input that they display. Pass the attributes necessary for styling, JavaScript functionality, etc., to the fields, and not just referring to the fields. Labels behave the same and can be accessed using field.label .

for , value , type , id and name do not need to pass, because they are processed automatically. There are some rules for handling special cases of attributes. If the attribute name is a Python keyword, such as class , add an underscore: class_ . Dashes are not valid Python names, so underscores between words are converted to dashes; data_toggle becomes data-toggle .

 {{ form.first_name(class_='validate') }} {{ form.first_name.label(class_='active') }} {{ form.begins(class_='datepicker', length=50) }} 

Please note that none of the related methods should be called directly, these documents simply describe the behavior when calling fields.

+10
source

In WTForms 2.1, I used extra_classes , as shown below:

1. The first way

 {{ f.render_form_field(form.first_name, extra_classes='ourClasses') }} 

or maybe in your case just like that:

 {{ form.first_name, extra_classes='ourClasses' }} 

We can also use the render_kw attribute in our form field, as shown below:

2. The second method

 style={'class': 'ourClasses', 'style': 'width:50%; other_css_style;'} first_name = StringField('First name', validators=[InputRequired(),Length(1, 64)], render_kw=style) 

But I would like to use the first method more.

+1
source

Source: https://habr.com/ru/post/1240409/


All Articles