簡體   English   中英

如何將flask wtform從擴展視圖移動到擴展視圖並實例化所有視圖的表單?

[英]How to move flask wtform from extending view to extended view and instantiate forms for all views?

為了使我的問題更清楚,這里有一個小應用程序,它接受句子輸入並輸出該句子兩次。

我有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)

現在,您將擁有在解壓縮上下文字典的所有模板中可用的上下文字典中添加的任何對象。

的index.html

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

base.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM