【问题标题】:jinja2 UndefinedError: 'resultado' is undefined | FLASKjinja2 UndefinedError: 'resultado' 未定义 |烧瓶
【发布时间】:2021-10-11 02:30:44
【问题描述】:

我正在使用 Flask。我有一条路线,我想在按下按钮时将其重定向到另一条路线,但我想传递一个参数。这是我的路线:

@app.route('/actualize_product.html', methods=['GET', 'POST'])
def actualize_product():
    if request.method == 'POST':
        print("post")
        query1 = """
            SELECT id FROM BD.producto
            WHERE id=""" + str(request.form['product_id'])
        conection = connect()
        resultt = conection.execute(query1)[0]
        print(resultt)
        return redirect(url_for('/edit_product.html', resultado = resultt)) #Line where I'm redirecting


    query = "SELECT * FROM BD.Producto ALLOW FILTERING; "
    conection = connect()
    result = conection.execute(query)
    return render_template('actualize_product.html', products = result)

这是我希望它被重定向的路线

@app.route('/edit_product.html', methods=['GET', 'POST'])
def edit_product():
    print("edit")
    if request.method == 'POST':
        
        print("Im already here")

    return render_template('edit_product.html')

问题是edit_product.html是我使用jinja2的文件

      <h2>Id del producto: {{resultado.id}} </h2> <br>
      <form action="app.py" method="get" onsubmit="return formEsValido()">
        <input type= "hidden" value = "{{resultado.id}}" id = "id" name = "id">
        <label for="product_name"> Nuevo nombre del Producto: </label>
        <input type="text" name="product_name" id="product_name" class="form-control">
        <label for="product_price"> Nuevo precio del Producto: </label>
        <input type="text" name="product_price" id="product_price" class="form-control">
        <label for="descripction"> Nueva descripcion del Producto: </label>
        <input type="text" name="description" id="description" class="form-control">
        <label for="stock">Nuevo stock del Producto</label>
        <input type="text" name="stock" id="stock" class="form-control">
        <br>  
        <button class="btn btn-primary"id="index-buttons" type="submit">Editar Producto</button>              
      </form>
  </div>

如果我使用 render_template 而不是重定向,它将不起作用,因为单击该按钮后,路由将是 /actualize_product.html 并且我希望它更改为 /edit_product.html' 因为我在那里有一个表单,我不知道如何使用重定向将名为“resultado”的变量传递给 jinja2。

【问题讨论】:

    标签: python html forms flask jinja2


    【解决方案1】:

    如果您只需要 id,您可以将其作为 url 参数传递。

    @app.route('/actualize')
    def actualize():
        return redirect(url_for('edit', id=123))
    
    @app.route('/edit')
    def edit():
        id = request.args.get('id')
        return render_template('edit.html', id=id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      相关资源
      最近更新 更多