Skip to main content
 首页 » 编程设计

python之Django:TypeError:必须是字符串,而不是 datetime.date

2025年05月04日24傻小

我在网上找到了一个练习,我正在尝试解决它。 这是我第一次使用 Django。

我有一个带有表单的页面。向用户显示一个字段(姓名、生日、电子邮件等),然后将这些值存储在用户的 session 中。

应用程序似乎在用户第一次提交表单时正常运行。申请人详细信息显示正确,检查数据库显示数据已正确存储在 session 中。

但是,在所有后续页面 View 中,应用程序崩溃并出现奇怪的错误,从错误中恢复的唯一方法是删除浏览器的 session cookie 或清除数据库中 session 的内容。

    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() 

请您参考如下方法:

回溯非常清楚。

datetime.strptime 方法接受一个字符串,例如

datetime.strptime('2015-11-11', '%Y-%m-%d') 

但是,在您的 hydrate 方法中,您向它传递了一个 datetime.date 对象,因此您会收到错误消息:

TypeError: must be string, not datetime.date