【问题标题】:Django: TypeError: must be string, not datetime.dateDjango:TypeError:必须是字符串,而不是 datetime.date
【发布时间】:2016-02-14 01:23:27
【问题描述】:

我在网上找到了一个练习,我正在尝试解决它。 这是我第一次接触 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()

【问题讨论】:

  • 在将值传递给 strptime 函数之前将其转换为字符串格式。 str(值)

标签: python django session


【解决方案1】:

回溯很清楚。

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

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

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

TypeError: must be string, not datetime.date

【讨论】:

  • 感谢 Alasdair,我应该如何继续?
  • 您需要调试代码并找出问题所在。也许水合物需要更改,以便它可以处理日期和字符串。或者水合物的调用值可能错误,或者水合物根本不应该被调用。我不知道,因为我认为您显示的代码不够多,而且我不熟悉您正在使用的库(TastyPie?)。
猜你喜欢
  • 1970-01-01
  • 2017-11-29
  • 2020-04-02
  • 2015-06-11
  • 2018-09-04
  • 2018-09-30
  • 2016-11-13
  • 2019-07-07
  • 1970-01-01
相关资源
最近更新 更多