javascriptflask-wtforms

Flask-wtf: set DecimalRangeField value from database on page load


I'm using flask-wtf with DecimalRangeField. I would like to set the range slider to a value from my database when I load the existing record into the form.

My form looks like:

downtime = DecimalRangeField(label='Outage/Downtime (hours)',
                             render_kw={"value": "0",
                                        "max": "5",
                                        "step": "0.5",
                                        "style": "--min: 0; --max: 5; --val: 0"
                                        },
                             )

Which renders a nice slider. The rendered HTML is:

<input id="downtime" max="5" name="downtime" step="0.5" style="--min: 0; --max: 5; --val: 0" type="range" value="0">
<label id="outage_slider_label">0</label>

I can use this and save the value to my database along with the rest of the form. However, when I load that record and try to have it show the slider value using some javascript it doesn't work.

I'm loading from the database in my 'get' route, like so:

form.downtime.data = change.downtime
print(f'downtime {form.downtime.data}')

for example if I saved 6 to my db, it does retrieve the correct value as evidenced by the print statement.

I then want to use some javascript to set the slider to the correct position and show this in the slider label. But when I do

let downtime_slider = document.getElementById('downtime')
console.log(downtime_slider.value)

It shows 0 not 6 (or whatever value comes from the db).

Why is this so?


Solution

  • I figured this out with some jinja2 magic.

    I put modified my template:

    <div class="ms-3">
      {{ form.downtime.label(class="form-label") }}
      {% if form.downtime.data %}
        {% set downtime_value = form.downtime.data %}
      {% else %}
        {% set downtime_value = 0 %}
      {% endif %}
      <div class="hstack gap-2">
        {{ form.downtime(class="range-slider", value=downtime_value) }}
        <label id="outage_slider_label">{{ downtime_value }}</label>
      </div>
    </div>
    

    Now when the page loads the slider sets to the correct position from what was in the database for the record. If there is no data (i.e. it is a new record) then the value is set to 0.

    Happy days!