The behavior of the following chunk of code has me tearing my hair out! It is from one of the 'routes' in a fairly complex Flask application, which I am writing to schedule Wemo devices. This is only a section of a much longer piece of code, and its purpose is to handle edits to the weekly 'pattern' for turning on (or off) a device at a given time. On the form that it is attached to, each day of the week is represented by a check box. If the name of the relevant checkbox ("Day_0" through "Day_6") exists in request.form (which is a dictionary), the box was checked. If the box was checked when the form was originally displayed, fields['pattern'][n] (where n corresponds to the Day #) is set to 1, if not, it is set to 0. In this code, 'changed' should be set to True if any of the check boxes has changed value.
The problem I am currently facing is that the code works as it should if a box that was originally displayed checked is unchecked by the user, but does not respond correctly if a box that was unchecked is checked by the user.
if 'Repeat' in request.form:
count=0
for daynum in range(0,7):
fldname='Day_'+ str(daynum)
if fldname in request.form:
flash(fldname + ': ' + str(fields['pattern'][daynum])) # added for debugging
mypattern.set_day(daynum)
count += 1
if fields['pattern'][daynum] != 1:
changed=True
flash('changed should be True') # added for debugging
elif fields['pattern'][daynum] == 1:
mypattern.reset_day(daynum)
changed=True
if count == 0:
errors=True
flash('Repeating actions must repeat on at least one day of the week')
else:
action.pattern=mypattern.encode()
What I have tried:
I have tried to determine why the if test fails. The bizarre thing is that the newly checked box is correctly detected, and the first debugging flash duly appears when the form reloads. This flash also correctly reports that the relevant fields['pattern'][n] value is 0. However, the test a couple of lines below, which should succeed (since the value is not equal to one), fails, and 'changed' is not set to True (and the second debugging flash does not appear). Can anyone make any sense out of this?