Flask-将表单输入传递给url_for

时间:2019-04-16 20:09:18

标签: python html flask

我有一个HTML模板,可让用户通过jQuery datepicker选择日期。

如何将选择的日期传递到动作中?

想法是,用户选择一个日期,然后通过app.route("/date/<date>")

传递到Flask的route.py

calendar.html

{% block topscripts %}
    <link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/calendar.css') }}">
    <script>
        $(function() {
            $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
        });
    </script>    
{% endblock %}

{% block content %}
<form method="post" action="{{ url_for('specific_date', date='2019-04-11') }}">
<p>Date: <input type="text" id="datepicker"  name='go-to-date'></p>
    <input type="hidden" name="calendar-form">
    <input type="submit">
</form>
{% endblock %}

因此,当用户在datepicker ID中选择一个日期时,我想将该日期传递给url_for。目前,我对日期(2019-04-11)进行了硬编码,只是为了检查它是否有效。我如何让该部分对用户在日历中选择的内容保持动态?

...如果有帮助,请参见routes.py(default_template()是最终渲染模板的函数)。

@app.route("/date/<date>/", methods=["GET", "POST"])
def specific_date(date):
    print("\n\nDate:", date, "\n\n")
    images = get_files_on(date)
    print("\n\nSpecific date images:", images)
    return default_template(date=date, image_list=images)

1 个答案:

答案 0 :(得分:2)

Make a POST request to the /date route like so.

Changes to calendar.html:

{% block content %}
<form method="post" action="{{ url_for('specific_date') }}">
<p>Date: <input type="text" id="datepicker"  name='go-to-date'></p>
    <input type="hidden" name="calendar-form">
    <input type="submit">
</form>
{% endblock %}

Changes to the date route:

from flask import request

# only allow POST request method
@app.route("/date/", methods=["POST"])
def specific_date():
    # getting the date from the POST request
    date = request.form['go-to-date']
    print("\n\nDate:", date, "\n\n")
    images = get_files_on(date)
    print("\n\nSpecific date images:", images)
    return default_template(date=date, image_list=images)