Call different function depending on whether it is first visit or after form submission in flask?

Issue

I want to set things up so if you go to mysite.com/calendar is has a default "start date" and "end date," but then there is a form submission button that regenerates the same page with the start and end date updated.

Right now, it basically works, but when you revisit mysite.com/calendar, it just sends the same form you sent the last time you were on the site. I want to make the site like this: when you first visit the page, the dates default to covering the last week, but then when you submit the form it reloads with the time period you selected.

Python/Flask Code

from flask import request


import os
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY

@app.route('/calendar', methods=['POST','GET'])
def calendar():
    start_date_dt=dt.datetime.now()-dt.timedelta(7)  #initialize start
    end_date_dt=dt.datetime.now()   #initialize end
        
if request.method == 'POST':
            start_date_dt=pd.to_datetime(request.form['start'])
            end_date_dt=pd.to_datetime(request.form['end'])         
                    
    av_start_date=start_date_dt.strftime('%Y-%m-%d %H:%M') #convert date to query format
    av_end_date=end_date_dt.strftime('%Y-%m-%d %H:%M')
    
    df= av_query(av_start_date,av_end_date,'44201') #perform query next 3 lines

#...do some stuff with query...omitted


    return render_template('calendar.html', title='Ozone Data',data_sets=zip(sites,datasets,cmap),sites=sites)

HTML Code

    <form action="{{url_for('calendar')}}" method="post" enctype="multipart/form-data">
      <label for="Start">Start:</label>
      <input type="date" id="start" name="start">
      
      <label for="End">End:</label>
      <input type="date" id="end" name="end">
      <input type="submit" value="Submit">
    </form>

Solution

You could pass your start and end dates to the value attribute of your start and end date inputs.

For demo purposes I’ve simplified your route code somewhat to focus on the problem in the question.

You could change your route to something like this:

@app.route("/calendar", methods=["POST", "GET"])
def calendar():
    start_date = dt.datetime.now() - dt.timedelta(7)
    end_date = dt.datetime.now()

    if request.method == "POST":
        start_date = request.form["start"]
        end_date = request.form["end"]

    return render_template("calendar.html", start_date=start_date, end_date=end_date)

and your template to this:

<form action="{{url_for('calendar')}}" method="post" enctype="multipart/form-data">
  <label for="Start">Start:</label>
  <input type="date" id="start" name="start" value={{start_date}}>
  <label for="End">End:</label>
  <input type="date" id="end" name="end" value={{end_date}}>
  <input type="submit" value="Submit">
</form>

If the form is posted the date from the inputs is used otherwise the default value is used.

If you want the dates from the form action to persist across reloads you could use something like Flask Session.

Answered By – Bas van der Linden

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published