烧瓶继续返回"用户名 - 此字段是必填字段。 "什么时候不问

时间:2015-04-20 04:22:09

标签: python flask flask-sqlalchemy flask-wtforms flask-login

我正在" cookiecutter-flask" (https://github.com/sloria/cookiecutter-flask)构建一个简单的Q& A应用程序。

所以我注册了一个名为"采访"的新蓝图。并将view.py设置为:

from flask import (Blueprint, request, render_template, flash, url_for,
                    redirect, session, )
from flask.ext.login import login_required
from nektime.interview.forms import InterviewForm
from nektime.utils import flash_errors

blueprint = Blueprint("interview", __name__, url_prefix='/interview',
                        static_folder="../static")


@blueprint.route("/", methods=['GET', 'POST'])
@login_required
def interview():
    form = InterviewForm(request.form)
    if form.validate_on_submit():
        new_answer = Answer.create(text=form.text.data)
        flash("Your answer has been submitted")
        return redirect(url_for('interview.interview'))
    else:
        flash_errors(form)
    return render_template("interview/interview.html", form=form)

和form.py到:

from flask_wtf import Form
from wtforms import TextField, TextAreaField
from wtforms.validators import DataRequired, Length

from nektime.models import Answer

class InterviewForm(Form):
    answer = TextAreaField('Answer',validators=[DataRequired(), Length(max=200)])

最后,model.py到:

class Answer(SurrogatePK, Model):
    __tablename__ = 'answers'
    text = Column(db.String(400), nullable=True)

html代码是:

{% extends "layout.html" %}

{% block content %}
<div class="body-content">
    <div class="row">
      <h1>INTERVEIW</h1>
      <p>This template was created by <a href="http://github.com/sloria/">Steven Loria</a> for use with the <a href="http://github.com/audreyr/cookiecutter/">cookiecutter</a> package by <a href="http://github.com/audreyr/">Audrey Roy</a>.</p>
    </div>
    <form method="POST" action="/" class="">
      {{ form.hidden_tag() }}
      {{ form.answer.label }} {{ form.answer(size=200) }}
      <input type="submit" value="Go">
    </form>
</div>
{% endblock %}

,结果如下:enter image description here

当我点击提交按钮时,页面会显示以下内容,并且当我没有输入任何相关代码时,我需要输入用户名和密码。

enter image description here

我试过了:

   -disabling other blueprints
   -disabling other layouts

但它会继续渲染此错误。我不知道那个错误。

1 个答案:

答案 0 :(得分:2)

flask cookiecutter 没有经验,但我注意到两件事:

您无需通过request.formflash_errors(form) wtforms 会自动为您执行此操作,因此您可能会更改为:

def interview():
    form = InterviewForm()
    if form.validate_on_submit():
        new_answer = Answer.create(text=form.text.data)
        flash("Your answer has been submitted")
        # I guess you want to redirect to / after form submission?
        return redirect(url_for('home')) # whatever home page?
    return render_template("interview/interview.html", form=form)

失败可能是由于:

<form method="POST" action="/" class="">

您要发布到"/"路由,而"/interview"视图应为interview以处理 POST 请求。