如何在 Flask 的会话中存储 WTForm 表单?
How to store WTForm Form in session in Flask?
我需要在会话中存储表单的结果,但我不断收到 TypeError: XXX is not JSON serializable for datetimes and Decimal fields。在请求之间保留表单数据的正确方法是什么?
这是我的表格:
class GiftRequestForm(Form):
giftee_name = StringField('Name',
[validators.Required(), validators.length(min=4, max=25)])
giftee_age = IntegerField('Age',
[validators.Required(),
validators.NumberRange(min=0, message="Age must be greater than 0")])
giftee_sex = RadioField('Gender',
[validators.Required()],
choices=[('0', 'Male'), ('1', 'Female')])
giftee_relationship = StringField('Relationship',
[validators.Required(), validators.length(min=4, max=25)],
description='Fill in the blank: The recipient is my _____.')
event = StringField('Event',
[validators.Required(), validators.length(min=4, max=80)])
event_date = DateField('Event Date',
[validators.Required()],
format='%Y-%m-%d',
description="Well have it to you at least four days before the event date.")
budget = DecimalField('Budget $',
[validators.Required(),
validators.NumberRange(min=0, message="Budget must be greater than 0")])
在我看来,我只想做:
form = GiftRequestForm()
...
session['gift_request_form'] = form
这根本不起作用,因为 GiftRequestForm 似乎无法 JSON 序列化。不幸的是,这也不起作用:
session['gift_request_form'] = form.data
因为我字典中的一个元素是日期时间和小数类型。所以我总是得到一个 TypeError: datetime.date(2015, 9, 2) is not JSON serializable,或者类似的 Decimal 字段。
这似乎是一个标准模式 -- 但我很难让它发挥作用。我应该怎么做?
我需要在会话中存储表单的结果,但我不断收到 TypeError: XXX is not JSON serializable for datetimes and Decimal fields。在请求之间保留表单数据的正确方法是什么?
这是我的表格:
class GiftRequestForm(Form):
giftee_name = StringField('Name',
[validators.Required(), validators.length(min=4, max=25)])
giftee_age = IntegerField('Age',
[validators.Required(),
validators.NumberRange(min=0, message="Age must be greater than 0")])
giftee_sex = RadioField('Gender',
[validators.Required()],
choices=[('0', 'Male'), ('1', 'Female')])
giftee_relationship = StringField('Relationship',
[validators.Required(), validators.length(min=4, max=25)],
description='Fill in the blank: The recipient is my _____.')
event = StringField('Event',
[validators.Required(), validators.length(min=4, max=80)])
event_date = DateField('Event Date',
[validators.Required()],
format='%Y-%m-%d',
description="Well have it to you at least four days before the event date.")
budget = DecimalField('Budget $',
[validators.Required(),
validators.NumberRange(min=0, message="Budget must be greater than 0")])
在我看来,我只想做:
form = GiftRequestForm()
...
session['gift_request_form'] = form
这根本不起作用,因为 GiftRequestForm 似乎无法 JSON 序列化。不幸的是,这也不起作用:
session['gift_request_form'] = form.data
因为我字典中的一个元素是日期时间和小数类型。所以我总是得到一个 TypeError: datetime.date(2015, 9, 2) is not JSON serializable,或者类似的 Decimal 字段。
这似乎是一个标准模式 -- 但我很难让它发挥作用。我应该怎么做?