在学习flask web开发这本书的时候,在第四章,遇到了一个问题。
按照书上,hello.py代码如下:
from flask import Flask, render_template from flask_bootstrap import Bootstrap from flask_moment import Moment from datetime import datetime from flask_wtf import Form from wtforms import StringField, SubmitField from wtforms.validators import Required app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' bootstrap = Bootstrap(app) moment = Moment(app) class NameForm(Form): name = StringField('What is your name?',validators=[Required]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html',name=name,form=form)
index.html代码如下:
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} <div class="page-header"> <h1>{% if name %}Hello,{{ name }}{% else %}Hello,Stranger{% endif %}!</h1> </div> {{ wtf.quick_form(form) }} {% endblock %}
之后在浏览器表单里输入内容提交后,会报错:
Traceback (most recent call last): File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/app.py", line 1641, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise raise value File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask/app.py", line 1625, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Users/lovehxy/Desktop/flask study/hello.py", line 24, in index if form.validate_on_submit(): File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/flask_wtf/form.py", line 156, in validate_on_submit return self.is_submitted() and self.validate() File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/wtforms/form.py", line 271, in validate return super(Form, self).validate(extra) File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/wtforms/form.py", line 130, in validate if not field.validate(self, extra): File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/wtforms/fields/core.py", line 175, in validate stop_validation = self._run_validation_chain(form, chain) File "/Users/lovehxy/.virtualenvs/flask/lib/python3.4/site-packages/wtforms/fields/core.py", line 195, in _run_validation_chain validator(form, self) TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given
求教是什么原因?
中间一行最后一个有误,Required需要加上()