DatePickerRange: set a maximum_nights like property


#1

In my dash app, I need my user to select a time period (in days). For that, I’m using a DatePickerRange.

However, I want to limit the max duration of this period — i.e., I don’t want the user to be able to select more than 1 month.

I know that the DatePickerRange has a minimum_nights property, but I haven’t found any maximum_nights.
➥ What is the best way to set a max limit to the period the user can select?

(I can imagine something with two date pickers with cross callbacks, but this doesn’t seems very “clean”)


#2

You could try to add a certain amount of days to the start_date property of the DatePicker.

Some code:

app.layout = html.Div([
             dcc.DatePickerRange(
                 id = 'datepicker',
                 minimum_nights=5,
                 clearable=True,
                 with_portal=True,
                 start_date=datetime.now().strftime('%m/%d/%y'))])

@app.callback(Output('datepicker', 'max_date_allowed'),
             [Input('datepicker', 'start_date')])
def set_max_data(start_date):
    start = datetime.strptime(start_date, "%m/%d/%y")
    end_date = start + timedelta(days=30)
    return end_date

using:

from datetime import datetime, timedelta

#3

You are right, this works… except that when I set the start_date, the end_date calendar dialog opens ; yet without the max_date_allowed fully working: you cannot select a date beyond start_date + 30, but those days are not greyed out (as the dialog might have been rendered before the max_date_allowed rule kicked in.

If you close and re-open the dialog, it works as expected.

However, you can understand that current state is not satisfactory as first scenario is the most frequent to occur.