【问题标题】:Flask, json, render_template, form action, data tablesFlask、json、render_template、表单动作、数据表
【发布时间】:2020-05-15 19:16:05
【问题描述】:

我希望发生这种情况:用户从表单下拉列表中进行选择,表单将变量传递给 Flask 服务器 app_route 函数,该函数调用由输入的参数动态过滤的 sql,并将数据表返回给浏览器。

在 Flask 中,我设置了一个 app_route,它提供 url_for 一个 json 文件。返回的对象是一个 json dict,它是由用户提交的表单中的参数过滤的 sql 查询的结果。表单的action函数发布到这个函数,并返回json dict url。

Datatable 需要数据的 url。它似乎不允许我使用 jinja 模板变量。我的冲突是我需要重定向/呈现具有数据表的 html 页面的模板并返回包含子字典的 url。

我要渲染模板('the_page_with_datatable.html', my_local_json_dict_variable)。

我可以从表单提交调用的 app_route 下调用的函数中 render_template('the_page_with_datatable.html') 或 return(my_local_json_dict_variable) 并分配给 url_for 位置,但不能同时使用两者。

这是怎么做到的?

所以我已经可以使用普通的 jinja 变量返回一个数据 frame_to_html,但我特别想要数据表功能。我不想渲染任何其他类型的表格。我还可以使用静态 sql 渲染数据表,其中我使用了对 api 的 sql 响应。问题是提交表单操作返回一个 url,而我需要两个 - json url 和 render_template url。

HTML/JS

<form class="form-inline" id="my_form" action="get_data" method="POST">
<div class="form-group">


              <select name="year" class="selectpicker form-control">
              {% for yr in years %}
                <option value="{{ yr }}">{{ yr }}</option>
              {% endfor %}
            </select>


        <select name="month" class="selectpicker form-control">
              {% for month in months %}
                <option value="{{ month }}">{{ month }}</option>
              {% endfor %}
            </select>

</div>
    <button type="submit" class="btn btn-default">Go</button>

</form>

<table id="values_table" class="table table-striped table-bordered" style="width:100%">

        <thead>

            <tr>

                <th>Name</th>
                <th>Number</th>
                <th>Date</th>
                <th>values_€</th>


            </tr>

        </thead>


    </table>




<script>

function setupData() {

    $(document).ready(function () {

       $('#values_table').DataTable( {
        dom: 'Bfrtip',


            "ajax": {


                "url": "/get_data",

                "dataType": "json",

                "dataSrc": "data",

                "contentType":"application/json"

            },

            "columns": [

                {"data": "PersonName"},
                {"data": "PersonNumber"},
                {"data": "Date"},
                {"data": "values_€"},

            ]

        });



    });

});
}

$( window ).on( "load", setupData );


</script>





Flask routes

#renders page with select form and datatable
@app.route("/values_select" , methods=['GET','POST'])
def values_select():
    years, months = api().values_select()
    return render_template('values_select.html', years=years, months=months)


#get json data for datatable to parse from url
@app.route("/get_data" , methods=['GET','POST'])
def get_data():
    year = request.form.get('year')
    month = request.form.get('month')
    data = assets_api().values(month, year)
    return jsonify(data=data)

【问题讨论】:

    标签: json ajax forms flask datatables


    【解决方案1】:

    最好有第二条返回json的路由,并利用数据表的ajax数据源。基本大纲:

    您的 json 路由(作为请求参数的下拉列表):

    @app.route('/get_data')
    def get_json():
        filter_val = request.args.get('filter')
    
        result = # Your query here (using filter_val, or all rows if none?)
    
        return jsonify(result)
    

    您当前的路线可能会保持原样,但是:

    def my_page():
        # ...
        return render_template('page.html')
    
    

    还有js:

    $('#table').DataTable( {
        ajax: {
            url: "{{ url_for('get_json') }}?filter=" + $("#dropdown").val(),
            dataSrc: ''
        },
        columns: [ ... ]
    } );
    

    这在数据表ajax 指南中有更多(更好)的详细说明。但我希望这是一个开始。

    编辑:

    这是一个设置,您可以稍微不同地处理重新获取数据。您不再需要该表格。您可以处理单击按钮或更改下拉菜单(如下)。调用table.reload() 函数将重新获取数据。比如:

    $("#the_dropdown").change(function() {
      table.reload();
    });
    

    【讨论】:

    • 感谢您提供此大纲。因此,如果在提交时设置了表单 action="get_data",则流程会将用户带到包含结果的 json 文件,而不是呈现 page.html。也许我需要 Ajax 将表单提交给 {{ url_for('get_json') }} 以触发函数 get_json(),但让浏览器停留在 page.html 上?
    • @user11764730 检查编辑,我一定是略过了表单有点抱歉。您不需要表单提交,因为它将由表格重新加载功能在页面上处理。希望这会有所帮助!
    猜你喜欢
    • 2022-08-19
    • 2014-09-13
    • 2019-04-27
    • 2021-10-15
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    相关资源
    最近更新 更多