VPfB
VPfB

Reputation: 17282

HiddenField not returning a value

I cannot find out why this code works with StringField, but not with HiddenField. The variable date2 was added just for debugging the issue.

(Actually, I can leave StringField there, but it took me some time to find the problem and I would like to understand what is wrong in order not to repeat the mistake)

Form definitions:

DAYS = 10
class _OneDayForm(Form):
    alarmtime = StringField(validators=[Optional(), validate_time])
    date2 = StringField()  # json encoded [Y,M,D]
    date = HiddenField()  # json encoded [Y,M,D]

class _PerDayForm(Form):
    days = FieldList(FormField(_OneDayForm), min_entries=DAYS)
    submit = SubmitField()

Jinja2 template:

    <input name="{{ subform.date.name }}" type="hidden" value="{{ ymd }}">
    <input name="{{ subform.date2.name }}" type="hidden" value="{{ ymd }}">

Generated HTML:

    <input name="days-0-date" type="hidden" value="[2016, 12, 7]">
    <input name="days-0-date2" type="hidden" value="[2016, 12, 7]">

StringField date2 returns its value, but HiddenField date does not. I tried to swap them to be sure that StringField vs. HiddenField really is the only difference.

Upvotes: 1

Views: 750

Answers (1)

VPfB
VPfB

Reputation: 17282

Just for the record, I have found the bug:

I was using {{ subform.hidden_tag() }} to display the CSRF token, but it does more than this (and I was not knowing it):

If your form has multiple hidden fields, you can render them in one block using hidden_tag().

So my hidden field was rendered twice and the first one had no value.

Upvotes: 2

Related Questions