1

我正在使用 WTForms 为烧瓶制作表格。这是相应的代码:

class UploadForm(flask.ext.wtf.Form):
    def __init__(self,year):
        flask.ext.wtf.Form.__init__(self)
        self.year=year
        subjects = app.config["SUBJECTS"][year]
        self.fichier = wtforms.fields.FileField(u'Fichier')
        self.subject = wtforms.fields.SelectField(u'Matière', choices=subjects)
        self.submit = wtforms.fields.SubmitField(u'Envoyer')

@app.route('/upload/<year>')
def upload(year):
    print year
    form = UploadForm(year)
    return flask.render_template('upload.html', form=form)

这是模板upload.html

{% extends "base.html" %}
{% block content %}
  <h2>Upload</h2>
  <form action="{{ url_for('get', year='1A') }}" method="post"
          enctype="multipart/form-data">
    {{ form.hidden_tag() }}

    {{ form.fichier.label }}
    {{ form.fichier }}

    {{ form.subject.label }}
    {{ form.subject }}

    {{ form.submit }}
  </form>
{% endblock %} 

但是当我运行它时,表单没有显示,而是我有这个:

<UnboundField(FileField, (u'Fichier',), {})> <UnboundField(SelectField, (u'Mati\xe8re',), {'choices': [('MA111', 'MA111'), ('NE111', 'NE111')]})>  <UnboundField(SubmitField, (u'Envoyer',), {})> 

有人可以帮我解决吗?

4

2 回答 2

3

您的问题是您正在创建没有任何字段的表单,然后在您的UploadForm.__init__方法中添加未绑定的字段。这个wtforms.form.Form类实际上在幕后做了很多元类魔法。做你正在做的事情的方法如下:

from flask import render_template
from flask.ext.wtf import Form
from wtforms.fields import FileField, SelectField, SubmitField

class UploadForm(Form):
    """This seemingly static class will be transformed
    by the WTForms metaclass constructor"""

    fichier = FileField(u'Fichier')
    subject = SelectField(u'Matière')
    submit = SubmitField(u'Envoyer')


@app.route('/upload/<year>')
def upload(year):
    subjects = app.config['SUBJECTS'][year]

    form = UploadForm()
    # We can set the choices dynamically, based on year
    form.subject.choices = subjects

    return render_template('upload.html', form=form)
于 2013-09-18T00:25:33.993 回答
3

表单的字段需要定义为类变量:

class UploadForm(flask.ext.wtf.Form):
    fichier = wtforms.fields.FileField(u'Fichier')
    subject = wtforms.fields.SelectField(u'Matière')
    submit = wtforms.fields.SubmitField(u'Envoyer')

    def __init__(self, year):
        flask.ext.wtf.Form.__init__(self)
        self.year=year
        self.subject.choices = app.config["SUBJECTS"][year]
于 2013-09-18T00:21:49.540 回答