我在网上找到了一个练习,我试图解决它。 这是我第一次使用Django。
我有一个带有表单的页面。向用户呈现字段(姓名,生日,电子邮件等),然后将值存储在用户的会话中。
当用户第一次提交表单时,该应用似乎正常工作。申请人的详细信息显示正确,并且检查数据库显示数据已在会话中正确存储。
但是,在所有后续页面视图中,应用程序崩溃时会出现奇怪的错误,从错误中恢复的唯一方法是删除浏览器的会话cookie或清除数据库中会话的内容
ERROR: test_create_applicant (api.test_views.ApplicantTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/test_views.py", line 30, in test_create_applicant
applicant = self.client.session.get_applicant_vo()
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/sessions/backends/custom_db.py", line 42, in get_applicant_vo
return ApplicantObject.hydrate(self.get('applicant') or {})
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/value_object/base.py", line 48, in hydrate
return cls(cls.hydrate_values(dehydrated or {}))
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/value_object/base.py", line 60, in hydrate_values
for name, field in cls.fields.iteritems()
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/value_object/base.py", line 60, in <dictcomp>
for name, field in cls.fields.iteritems()
File "/Users/pablo/Desktop/exercise-misbehaving-application/api/value_object/fields.py", line 300, in hydrate
return None if value is None else datetime.strptime(value, '%Y-%m-%d').date()
TypeError: must be string, not datetime.date
有人能指出我正确的方向吗?
class Date(Field):
"""
A field that contains a date object.
"""
def hydrate(self, value):
return None if value is None else datetime.strptime(value, '%Y-%m-%d').date()
def dehydrate(self, value):
"""
:type value: datetime.date
"""
return None if value is None else value.strftime('%Y-%m-%d')
def make_public_value(self, value):
"""
:type value: datetime.date
"""
return None if value is None else value.isoformat()
答案 0 :(得分:1)
回溯非常清楚。
datetime.strptime
方法采用字符串,例如
datetime.strptime('2015-11-11', '%Y-%m-%d')
但是,在hydrate
方法中,您已将datetime.date
对象传递给它,因此您收到错误消息:
TypeError: must be string, not datetime.date