You need to enable JavaScript to run this app. Django表单date_of_death测试报错:1900-01-01与预期日期不符
优惠活动
大模型
产品
解决方案
定价
更多

Django表单date_of_death测试报错:1900-01-01与预期日期不符

问题根因说明

  1. 测试对象理解错误
    你访问的author-create是「创建新作者」的视图,返回的表单是供用户填写新作者信息的空白表单,和你在setUp方法中创建的已存在Author实例没有任何关联,所以你给该实例设置的date_of_death值不会出现在新建表单的初始值里。

  2. 日期解析格式错误
    你代码中datetime.datetime.strptime(response_date, "DD/MM/YYYY")的格式符是无效的:Python的strptime规范中,日对应的格式符是%d、月是%m、年是%Y,你写的DD/MM/YYYY无法正确解析日期,1900-01-01就是格式解析失败后返回的错误默认值,不是Django日期字段的原生默认值。

  3. 表单初始值未配置
    这个测试的预期是要求你在新建作者的表单中为date_of_death设置默认初始值,你没有在表单类或视图中做对应的配置,自然拿不到预期的2020-06-11。


解决步骤

  • 修正测试代码中的日期解析格式,将对应行改为:
response_date = datetime.datetime.strptime(response_date, "%d/%m/%Y").date()
  • 在你的AuthorCreate视图或关联的表单类中配置初始值:
    方案1(表单类配置):
    from django import forms
    from .models import Author
    import datetime
    
    class AuthorForm(forms.ModelForm):
        date_of_death = forms.DateField(initial=datetime.date(2020, 6, 11))
        class Meta:
            model = Author
            fields = '__all__'
    
    方案2(视图类配置):
    from django.views.generic.edit import CreateView
    from .models import Author
    import datetime
    
    class AuthorCreate(CreateView):
        model = Author
        fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
        
        def get_initial(self):
            initial = super().get_initial()
            initial['date_of_death'] = datetime.date(2020, 6, 11)
            return initial
    

内容的提问来源于stack exchange,提问作者Calvin Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 17:12:02