Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

python - rendering forms with flask + wtform

code in question:

from flask import Blueprint, render_template, abort
from flask.ext.wtf import Form
import os
from jinja2 import TemplateNotFound
from models import Member
from wtforms.ext.sqlalchemy.orm import model_form
@simple_page.route('/register')
def register():
    form = model_form(Member, Form)
    return render_template('register.html', form=form, name="bad")


class Member(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(50), nullable=False, unique=True)

and in my view:

        <p class="txt11 colorb">
        {{ form.name }}
        </p>

this outputs <UnboundField(TextField, (), {u'default': None, u'filters': [], u'validators': [<wtforms.validators.Required object at 0x7f62f59b5590>, <wtforms.validators.Length object at 0x7f62f59b55d0>]})>, not an actual field. how do i get an actual form/field with the wtform?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're passing a form class not a form instance to the template. The model_form method generates a new class dynamically, which can be re-used, extended, and otherwise used like any other form subclass. It's also quite un-necessary to generate this form class on every run of your view, so you can move this call outside of your view.

You passing an uninstantiated class is also why you get strange behavior relating to UnboundField (which is how WTForms handles declarative field instantiation)

The fix is simple:

MemberForm = model_form(Member, base_class=Form)

@simple_page.route('/register')
def register():
    form = MemberForm(name=u'bad')
    return render_template('register.html', form=form)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...