Syncing URL Session Arguments from Widget Value

Hey everyone!
I am building a dashboard, it’s URL looks like this

http://10.0.1.85:9990/main?from=2021-10-04&to=2021-10-10&field_id=2284811

From it, I take the sessions arguments (from, to, field_id) using

pn.state.session_args.get('from')[0].decode('UTF-8')

And set it as the default value of three widgets using -

date_from_wig = pn.widgets.DatetimeInput(name='From', value=pd.to_datetime(pn.state.session_args.get('from')[0].decode('UTF-8')))

I am trying to update the URL of the session when a widget value changes using -

if pn.state.location:
    pn.state.location.sync(date_from_wig, {'value': 'from'})

Thing is - I want to reformat the widget value, basically doing something like this -

pn.state.location.sync(date_from_wig, {pd.to_datetime('value').strftime("%Y-%m-%d"): 'from'})

Do you have any idea how I can manipulate the value from the widget before syncing it to the session URL?
Thanks!

I think you are over complicating some part of you code.

If I replace DatetimeInput with DatePicker something like the following will work:

import panel as pn
import param
from datetime import date
pn.extension()


def main():
    start = pn.widgets.DatePicker(name="Start date", value=date.today())
    end = pn.widgets.DatePicker(name="End date", value=date.today())
    field = pn.widgets.IntInput(name="Field ID", value=1)

    if pn.state.location:
        pn.state.location.sync(start, {"value": "from"})
        pn.state.location.sync(end, {"value": "to"})
        pn.state.location.sync(field, {"value": "field_id"})

    return pn.Column(start, end, field)


pn.panel(main).servable()

If you want an Input instead of DatePicker, a small hack is needed to change the param.Date to param.CalendarDate for the widget like and change the format:

class DateInput(pn.widgets.DatetimeInput):
    format = param.String(default=r'%Y-%m-%d')
    value = param.CalendarDate(default=None)

And then replace pn.widgets.DatePicker with DateInput in the first code block.

1 Like