【问题标题】:How to load dropdowns and pass values using flask如何使用烧瓶加载下拉列表和传递值
【发布时间】:2021-10-27 05:15:43
【问题描述】:

使用 Python 和 Flask 我有这个 Flask 文件,它应该从用户那里获取一些输入并将这些输入传递给要使用的 python 脚本。我可以得到 2 个可以接受数字作为输入的框,并且使用下面的代码可以正常工作。

from flask import Flask, request, render_template
import os
import csv
import fileinput
import codecs
import re
import pandas as pd
import os
from pandas.core.dtypes.missing import notnull   
from races import calculate_mode
from races import do_calculation
#import races
app = Flask(__name__)

app.config["DEBUG"] = True

inputs = []
    @app.route("/testing", methods=["GET", "POST"])
    def testing():
        errors = ""        
        number1 = None
        number2 = None
        colours = ['Red', 'Blue', 'Black', 'Orange']
    
        if request.method == "POST":
    
            try:
                number1 = float(request.form["number1"])
            except:
                errors += "<p>{!r} is not a number.</p>\n".format(request.form["number1"])
            try:
                number2 = float(request.form["number2"])
            except:
                errors += "<p>{!r} is not a number.</p>\n".format(request.form["number2"])
    
        if number1 is not None and number2 is not None:
            result = do_calculation(number1, number2)
            
            return '''
                <html>
                    <body>
                        <p>The result is {result}</p>
                        <p><a href="/">Click here to calculate again</a>
                    </body>
                </html>
            '''.format(result=result)
    
        return '''
            <html>
                <body>
                    {errors}
                    <p>Enter your numbers:</p>
                    <form method="post" action=".">
                        <p><input name="number1" /></p>
                        <p><input name="number2" /></p>
                        <p><input type="submit" value="Do calculation" /></p>
                    </form>
                </body>
            </html>
        '''.format(errors=errors)

if __name__ == "__main__":
    app.run(debug=True)

但对于这个应用程序,它确实需要下拉框。我得到了一个下拉框来使用这样的东西加载:

@app.route("/dropdown", methods=["GET", "POST"])
def select():

    colours = ['Red', 'Blue', 'Black', 'Orange']
    return render_template('select.html', colours=colours)

但是我不知道如何从新加载的页面和 python 文件中传递参数。因此,我试图通过将第二个“return”替换为下面的代码(与使用 select.html 加载的文件基本相同)来将 html 加载到同一个文件中,但无法获得下拉菜单工作(错误是 KeyError: '% for color in colours')

return '''
    <html>
        <form>
            <select name="colour" method="POST" action="/">
                <option value="{{colours[0]}}" selected>{{colours[0]}}</option>
                {% for colour in colours[1:] %}
                    <option value="{{colour}}">{{colour}}</option>
                {% endfor %}
            </select>
            <p><input type="submit" value="Do calculation" /></p>
        </form>
    </html>
'''.format(errors=errors)

有谁知道为什么它不起作用,或者对如何做到这一点有更好的想法?

【问题讨论】:

  • 您的新 return 不会运行 render_template,因此它不会得到 colours。您应该先生成字符串,然后再使用return render_template_string(new_string, colours=colours)。或者甚至您可以直接将错误发送到模板return render_template_string(new_string, colours=colours, errors=errors) 而无需使用.format()
  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。

标签: python html flask


【解决方案1】:

您的问题是您使用.format() 来格式化HTML,而format 将所有{ } 视为变量的位置——甚至{%...%}——它不知道这{% ... %} 是什么意思。

您应该使用render_template_string() 而不是format()

if number1 is not None and number2 is not None:
            result = do_calculation(number1, number2)

            html = '''
                <html>
                    <body>
                        <p>The result is {{ result }}</p>
                        <p><a href="/">Click here to calculate again</a>
                    </body>
                </html>
            '''
  
            return render_template_string(html, result=result)

html =  '''
    <html>
        <form>
            {{ errors }}
            <select name="colour" method="POST" action="/">
                <option value="{{ colours[0] }}" selected>{{colours[0]}}</option>
                {% for colour in colours[1:] %}
                    <option value="{{ colour }}">{{ colour }}</option>
                {% endfor %}
            </select>
            <p><input type="submit" value="Do calculation" /></p>
        </form>
    </html>'''


return render_template_string(html, colours=colours, errors=errors)

if number1 is not None and number2 is not None:
            result = do_calculation(number1, number2)
  
            return render_template_string('''
                <html>
                    <body>
                        <p>The result is {{ result }}</p>
                        <p><a href="/">Click here to calculate again</a>
                    </body>
                </html>
            ''', result=result)


return render_template_string('''
    <html>
        <form>
            {{ errors }}
            <select name="colour" method="POST" action="/">
                <option value="{{ colours[0] }}" selected>{{colours[0]}}</option>
                {% for colour in colours[1:] %}
                    <option value="{{ colour }}">{{ colour }}</option>
                {% endfor %}
            </select>
            <p><input type="submit" value="Do calculation" /></p>
        </form>
    </html>''', colours=colours, errors=errors)

【讨论】:

  • 这很有帮助。你知道如何返回选定的值吗?我尝试在这一行添加一个名称: 然后尝试类似: colorselected = request.form["colorselected"] 但我不断收到 BadRequestKeyError: 400 KeyError: 'colorselected'
  • 你有&lt;select name="colour" &gt;,你应该使用request.form["colour"]。将名称放入 option 是没有用的 - 浏览器将使用来自 &lt;select&gt;name 发送选定的值。而且你甚至没有在&lt;option&gt; (&lt;option name=...&gt;) 中输入名字,而是在&lt;option&gt;&lt;/option&gt; 之间的HTML 中输入名称
猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 2020-06-21
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多