How can I specify which widget I want (e.g. a TextArea rather than a simple Text input) from a model generated form? Flask SQLAlchemy WTForms

StackOverflow https://stackoverflow.com/questions/21285196

Вопрос

I've used the snippets from http://flask.pocoo.org/snippets/60/ to create a WTForms form from my model in Flask. Everything works fine except from the fact that it only creates input fields. I want the description (see models.py below) to be a textarea. Any ideas?

From models.py:

title = db.Column(db.String(55))
description = db.Column(db.Text)

From views.py

MyForm = model_form(MyModel, base_class=Form)
form = MyForm()
return render_template('create.html', form=form)

From create.html

{% for field in form %}
    {{field.label}}
    {{field}}
{% endfor %}

Output:

<input id="title" name="title" type="text" value="">
<input id="description" name="description" type="text" value="">

What I want:

<input id="title" name="title" type="text" value="">
<textarea id="description" name="description"></textarea>
Это было полезно?

Решение

You can use the field_args argument of model_form to override settings for specific fields. You can set everything from the label to the validators. It accepts any valid argument for Field.__init__(), including the widget.

MyForm = model_form(MyModel, base_class=Form, field_args={
    'description': {'widget': TextArea()},
})

If you want to see what else you can override, take a look at the source for Field.

Другие советы

You can create a custom form like so:

forms.py

from flask.ext.wtf import Form
from wtforms.fields import TextField, TextAreaField, SubmitField
import wtforms

class ItemForm(Form):
    title = Textfield('Title')
    description = TextAreaField('Description')
    submit = SubmitField('Submit')

routes.py

from forms import ItemForm
@app.route('/form')
def form()
    form = ItemForm()
    return render_template('form.html', form=form)

form.html

{% for field in form %}
    {{field.label}}
    {{field}}
{% endfor %}

This tutorial has more info: http://net.tutsplus.com/tutorials/python-tutorials/intro-to-flask-adding-a-contact-page/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top