如何将flask wtform从扩展视图移动到扩展视图,并为所有视图实例化表单?

2024-10-02 22:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有base.html

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

index.html

^{pr2}$

以下是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页面。如何将窗体移动到基本.html并为所有扩展的视图实例化窗体base.html?在


Tags: pyformbaseindexreturntitlehtmlbody
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:53

You can use the flask.g object and ^{}.

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="")

也可以显式定义上下文函数

^{pr2}$

是这样用的

@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>

相关问题 更多 >