首页 > 解决方案 > Python Flask 出错:jinja2.exceptions.UndefinedError: 'form' is undefined

问题描述

这是我的应用程序 drop.py:

#!/usr/bin/env python
from flask import Flask, flash, redirect, render_template,request, url_for
from flask_wtf import Form
from wtforms import DateField
from datetime import date

app = Flask(__name__,template_folder='template')

class DateForm(Form):
    dt = DateField('Pick a Date', format="%m/%d/%Y")


@app.route('/')
def index():
    return render_template(
        'index.html',
        data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}],data2=[{'name':'John'}, {'name':'Mouton'}, {'name':'Blah'}])

@app.route("/" , methods=['GET', 'POST'])
def test():
    select = request.form.get('comp_select')
    if select == "red":
        col = "Rouge"
    elif select == "green":
        col = "Vert"
    elif select == "blue":
        col = "Bleu"

    select2 = request.form.get('comp_select2')
    if select2 == "John":
        usr = "Personne"
    elif select2 == "Mouton":
        usr = "Animal"
    elif select2 == "Blah":
        usr = "Autre"

    text = request.form['text']

@app.route('/', methods=['post','get'])
def home():
    form = DateForm()
    if form.validate_on_submit():
        mydate =  form.dt.data.strftime('%x')
    return render_template('index.html', form=form)

    return(str(col)+str("\n\n")+str(usr)+str("\n\n")+str(text)+str("\n\n")+str(mydate))


if __name__=='__main__':
    app.run(debug=True,host="0.0.0.0")


这是我在模板文件夹下的 index.html :

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>DatePicker Example</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
    $(function() {
        $( ".dtpick" ).datepicker();
    });
    </script>
</head>
<body>
<form class="form-inline" method="POST" action="{{ url_for('test') }}">
  <div class="form-group">
    <div class="input-group">
        <span class="input-group-addon">Please select</span>
            <select name="comp_select" class="selectpicker form-control">
              {% for o in data %}
              <option value="{{ o.name }}">{{ o.name }}</option>
              {% endfor %}
            </select>
<form class="form-inline" method="POST" action="{{ url_for('test') }}">
        <span class="input-group-addon">Please select</span>
            <select name="comp_select2" class="selectpicker form-control">
              {% for o in data2 %}
              <option value="{{ o.name }}">{{ o.name }}</option>
              {% endfor %}
            </select>
<form method="POST">
            <input name="text">
<form method="post" action="">
    {{ form.hidden_tag() }}
    {{ form.dt(class="dtpick") }}
    <button type="submit">Go</button>
    </div>
  </div>
</form>
</form>
</form>
</form>
</body>
</html>

我需要用户选择名称、颜色、输入自由文本并选择日期。我曾尝试修改 python 代码和 html 文件,但我总是遇到此错误,即未定义表单。

如果我删除 Datepicker 的部分,一切正常。(下拉菜单、自由文本、按钮)

标签: pythonflask

解决方案


问题出现在您的index()函数中。您不像在函数中那样form=form向调用提供。添加这个至少应该解决这个问题。需要明确一点:由于同一条路线有多个功能,您应该首先让第一个工作。您在第一个函数中需要一个表单,但由于缺少令牌,以下会导致 RuntimeError:render_template()home()

@app.route('/')                                                                     
def index():                                                                        
    form = DateForm()                                                               
    if form.validate_on_submit():                                                  
        mydate =  form.dt.data.strftime('%x')                                      
    return render_template(                                                         
        'index.html',                                                               
        data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}],data2=[{'name':'John'}, {'name':'Mouton'}, {'name':'Blah'}],    
        form=form                                                                   
    )

我们可以通过在实例化 Flask 之后设置一个密钥来解决 RuntimeError(只是一个示例密钥):

app.secret_key = 'aaaaaaaaa'

之后,我在浏览器中得到一个表单。


推荐阅读