【问题标题】:POST date values in django testCase在 django testCase 中发布日期值
【发布时间】:2014-12-02 00:38:19
【问题描述】:

我正在尝试编写一个测试来注册用户。我无法验证表单,因为我不知道如何向表单提交有效日期。这是有问题的代码:

class AccountManagementTest(TestCase):
    def test_signup(self):
        response = self.client.post(reverse('register'), {
            'first_name': 'Gandalf', 
            'last_name': 'TheGrey', 
            'email': 'gandalf@me.com', 
            'password1': 'SauronSucks', 
            'password2': 'SauronSucks', 
            'birthdate': datetime(1956, 1, 1),
            'tos': True})

之后我可以输出response.content,表单中的错误是“请输入有效日期”。我没有覆盖表单中birthdateclean 方法。这是表单中日期字段的声明:

birthdate = forms.DateField(
        widget=SelectDateWidget(
            years=range(this_year-90, this_year-12)[::-1]),
            required=True,)

我怎么给它发送一个有效的日期?

【问题讨论】:

    标签: python django testing


    【解决方案1】:

    您需要传递与默认input_formats 之一匹配的日期的字符串表示

    ['%Y-%m-%d',      # '2006-10-25'
    '%m/%d/%Y',       # '10/25/2006'
    '%m/%d/%y']       # '10/25/06'
    

    在您的情况下,例如:

    'birthdate': '1956-01-01'
    

    【讨论】:

      【解决方案2】:

      在 Python 中,datetime 和 date 不是同一个对象。 datetime 包含诸如小时、分钟、秒等信息。

      看这里:https://docs.python.org/2/library/datetime.html

      如果生日是 Django 中的 DateField,你需要写:

      'birthdate': date(1956, 1, 1)(不要忘记为此导入 datetime.date)

      【讨论】:

        猜你喜欢
        • 2022-01-26
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多