我是Flask的新手,并尝试使用flask建立简单的用户窗体页面,并遇到错误。当我尝试仅渲染纯HTML并扩展base.html时,一切工作正常,但是添加宏后,结果如下。我尝试了所有事情,但无法独自解决问题。有什么提示,我在做什么错?
[2019-07-09 22:19:39,837] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "path/venv/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "path/venv/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "path/venv/lib/python3.6/site-packages/flask/app.py", line 1967, in finalize_request
response = self.make_response(rv)
File "path/venv/lib/python3.6/site-packages/flask/app.py", line 2130, in make_response
" {rv.__class__.__name__}.".format(rv=rv)
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a UserForm.
127.0.0.1 - - [09/Jul/2019 22:19:39] "GET / HTTP/1.1" 500 -
这是我的Python代码:
from app import app
from flask import render_template
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SelectField
from wtforms.validators import InputRequired
@app.route('/', methods=['GET', 'POST'])
class UserForm(FlaskForm):
prefix = StringField("Prefix", validators=[InputRequired()])
anrede = StringField("Anrede", validators=[InputRequired()])
def form():
form = UserForm()
return render_template('html_one_flask.html', form=form)
我要加载的表单
{% extends "base.html" %}
{% from "render_field.html" import render_field %}
{% block content %}
<div class = "container">
<div class = "spacer" > </div>
</div>
<div class = "container" id = "data_category">PERSONAL DATEN</div>
<div class = "container">
<div class = "spacer" > </div>
<div class="form-group row flex-v-center" id = 1>
{{ render_field(form.prefix), placeholder = form.prefix.label.text }}
{{ render_field(form.anrede), placeholder = form.anrede.label.text }}
</div>
</div>
{% endblock %}
和从另一个文件导入的宏
{% macro render_field(field) %}
<div class = "col-0.75">
<div class = "spacer_label" > </div>
<label for="{{ field.name }}">{{ field.label.text }} </label>
</div>
<div class = "col-1">
{{ field(class_ = "form-control input-sm", **kwargs|safe }}
</div>
{% endmacro %}
答案 0 :(得分:2)
您的@app.route
应该在view函数上方,而不是在类声明上方:
@app.route('/', methods=['GET', 'POST'])
def form():
...
答案 1 :(得分:0)
您将@ app.route装饰器放在了黄色的地方