assigning css class to form element passed from fl

2019-08-16 13:51发布

问题:

I am quite new to jinja / flask, I am creating dymnamic form in my flask app:

class CreateForm(FlaskForm):
    searchCity = StringField('View forcast of city:', validators=[InputRequired("Please enter the city you want to check weather updates")])
    count = IntegerField("Days")
    submit = SubmitField("Submit")


form = CreateForm(request.form)
form.count.default = count
form.count.label = "Days" if count > 1 else "Day" 

form.count.data = count

and in jinja template:

<form>
    <dl>
        <dd>{{ form.searchCity.label }} {{ form.searchCity(size=20) }} 
            for next {{ form.count(size=2) }} {{ form.count.label }}
            <input type="submit" class="btn-primary" value="Submit" id="calculate" onclick="getWeatherForcaset(
            document.getElementsByName('searchCity')[whole_number].value,
            document.getElementsByName('count')[whole_number].value
            );" >
        </dd>
        <dd>
            <input type="checkbox" name="exactMatch" checked="checked">Exact Match 
            &nbsp;
            <input type="checkbox" name="remember">Remember<br/ >
        </dd>

    </dl>
 </form>

I want to assign class form-group to searchCity inputbox ! any help would be greatly appreciated thanks

回答1:

You should be able to pass variables into the constructor like so

{{ form.searchCity(size=20, class_='searchCity') }}  

Documentation is available at :

http://wtforms.readthedocs.io/en/latest/crash_course.html#rendering-fields

Doc Snippet

However, the real power comes from rendering the field with its call() method. By calling the field, you can provide keyword arguments, which will be injected as html attributes in the output:

form.content(style="width: 200px;", class_="bar")

<input class="bar" id="content" name="content" style="width: 200px;" type="text" value="foobar" />'