How to resolve a NameError: global name 'ContactForm' is not defined
我在 Flask 中创建了一个联系表单,但它不起作用。它给出了错误 NameError: global name 'ContactForm' is not defined
自定义形式为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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 是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) |
我该如何解决这个问题?
创建一个名为 forms.py 的新文件并在其中插入以下代码。那么你的代码应该可以工作了。
1 2 3 4 5 6 7 8 9 10 11 | 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") |
首先,你有安装flask-wtf 吗?
试试这个: