如何将烧瓶 wtform 从扩展视图移动到扩展视图,并实例化所有视图的表单



为了使我的问题更清楚,这里有一个小应用程序,它接受句子输入并输出该句子两次。

我有base.html

<html>
  <head>
    <title> My site </title>
    <body>
    {% block content %}{% endblock %}
   </body>
</html>

index.html

{% extends "base.html" %}
{% block content %}
{{ s }}
<form action="" method="post" name="blah">
    {{ form.hidden_tag() }}
    {{ form.sentence(size=80) }}
    <input type="submit" value="Doubler"></p>
</form>
{% endblock %}

这是views.py的一部分:

from forms import DoublerForm
@app.route('/index')
def index():
    form = DoublerForm()
    if form.validate_on_submit():
        s = form.sentence.data
        return render_template('index.html', form=form, s=str(s) + str(s))
    return render_template('index.html', form=form, s="")

这是forms.py,没有所有的导入:

class DoublerForm(Form):
    sentence = StringField(u'Text')

这似乎工作正常。但是我想要的是将我的输入表单放在base.html模板中,以便它显示在扩展它的所有页面上,而不仅仅是index页面。如何将窗体移动到 base.html并为扩展 base 的所有视图实例化窗体.html?

您可以使用 flask.g 对象并flask.before_request

from flask import Flask, render_template, g
from flask_wtf import Form
from wtforms import StringField
@app.before_request
def get_default_context():
    """
    helper function that returns a default context used by render_template
    """
    g.doubler_form = DoublerForm()
    g.example_string = "example =D"
@app.route('/', methods=["GET", "POST"])
def index():
    form = g.get("doubler_form")
    if form.validate_on_submit():
        s = form.sentence.data
        return render_template('index.html', form=form, s=str(s) + str(s))
    return render_template('index.html', form=form, s="")

您还可以显式定义上下文函数

def get_default_context():
    """
    helper function that returns a default context used by render_template
    """
    context = {}
    context["doubler_form"] = form = DoublerForm()
    context["example_string"] = "example =D"
    return context

并像这样使用

@app.route('/faq/', methods=['GET'])
def faq_page():
    """
    returns a static page that answers the most common questions found in limbo
    """
    context = controllers.get_default_context()
    return render_template('faq.html', **context)
现在,您将拥有添加到上下文字典的任何对象

,这些对象都可以在解压缩上下文字典的所有模板中使用。

索引.html

{% extends "base.html" %}
{% block content %}
{{ s }}
{% endblock %}

基地.html

<html>
  <head>
    <title> My site </title>
    <body>
    {% block content %}{% endblock %}
    <form action="" method="post" name="blah">
      {{ doubler_form.hidden_tag() }}
      {{ doubler_form.sentence(size=80) }}
      {{ example_string }}
      <input type="submit" value="Doubler"></p>
    </form>
   </body>
</html>

最新更新