1

我在 Flask 中创建了一个联系表单,但它不起作用。它给出了错误 NameError: global name 'ContactForm' is not defined

自定义表格是:

<form action="{{ url_for('contact') }}" method=post>
    {{ form.hidden_tag() }}

    {{ form.name.label }}
    {{ form.name }}

    {{ form.email.label }}
    {{ form.email }}

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

    {{ form.message.label }}
    {{ form.message }}

    {{ form.submit }}
  </form>

routes.py 是:

from flask import Flask, render_template
from forms import ContactForm
app = Flask(__name__)     

def contact():
    form = ContactForm()

    if request.method == 'POST':
        return 'Form posted.'

    elif request.method == 'GET':
        return render_template('contact.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

我该如何解决问题?

4

2 回答 2

1

创建一个名为 forms.py 的新文件并在其中插入以下代码。然后你的代码应该可以工作。

from flask.ext.wtf import Form

from wtforms import TextField, TextAreaField, SubmitField, validators


class ContactForm(Form):
    name = TextField("Name", [validators.Required()])
    email = TextField("Email", [validators.Required(), validators.email()])
    subject = TextField("Subject", [validators.Required()])
    message = TextAreaField("Message", [validators.Required()])
    submit = SubmitField("Send")
于 2013-10-16T04:55:25.623 回答
0

首先,你有安装flask-wtf 吗?
试试这个: form = ContactForm(request.form)

于 2013-10-14T20:50:09.777 回答