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.email.label }} {{ form.subject.label }} {{ form.message.label }} {{ form.submit }} |
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(): if request.method == ‘POST’: elif request.method == ‘GET’: if __name__ == ‘__main__’: |
我该如何解决这个问题?
- stackoverflow.com/questions/17926869/…?
- @Brar:”无法导入 XXX”是一个非常常见的 Python 错误消息,通常与您的代码无关,而是您的环境设置不正确(换句话说,您没有正确安装包,或者您将其安装在错误的位置)。您是否正确安装了 Flask-WTF?
- 请大家提供另一种解决方案来解决它
创建一个名为 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): |
首先,你有安装flask-wtf 吗?
试试这个:form = ContactForm(request.form)
来源:https://www.codenong.com/19354141/