1

I have an HTML template that lets the user select a date via jQuery datepicker.

How can I pass the date selected into an action?

The idea is, the user selects a date, then that passes to Flask's route.py, via app.route("/date/<date>")

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 %}

So, when the user selects a date in the datepicker ID, I want to pass that date to the url_for. Currently I hardcoded the date (2019-04-11) just to check that it works, and it does. How can I have that part be dynamic to whatever the user selects in the Calendar?

...If it helps, here's in routes.py (default_template() is the function that renders the template in the end).:

@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 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! I got so caught up in trying to do optional variables, I forgot I could do this instead. Thanks for the help!
I'm glad I could be of help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.