Django使用datetime.date()作为DateField的输入实现过去日期的输入
Django use datetime.date() as input for DateField to achieve past date input
我有一个简单的模型,我想在模型中输入过去的日期作为 DateField。
import datetime
class BalanceSheet(models.Model):
ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet")
date = models.DateField(default=datetime.date)
但是当我尝试在管理面板中添加记录时收到以下错误
TypeError at /admin/financials/balancesheet/add/
function missing required argument 'year' (pos 1)
Request Method: GET
Request URL: http://localhost:8000/admin/financials/balancesheet/add/
Django Version: 3.1
Exception Type: TypeError
Exception Value:
function missing required argument 'year' (pos 1)
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 831, in get_default
Python Executable: /usr/local/bin/python
Python Version: 3.7.8
Python Path:
['/code',
'/usr/local/lib/python37.zip',
'/usr/local/lib/python3.7',
'/usr/local/lib/python3.7/lib-dynload',
'/usr/local/lib/python3.7/site-packages']
Server time: Sun, 09 Aug 2020 11:40:48 +0000
您传递的默认值需要一个参数,这就是您收到错误的原因。如果您通过 datetime.date.today
,您可以在创建记录后将日期更改为之前的日期。
尝试替换
...
date = models.DateField(default=datetime.date)
与:
import datetime
...
date = models.DateField(default=datetime.date.today)
或者:
from datetime import datetime
...
date = models.DateField(default=datetime.now)
我有一个简单的模型,我想在模型中输入过去的日期作为 DateField。
import datetime
class BalanceSheet(models.Model):
ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet")
date = models.DateField(default=datetime.date)
但是当我尝试在管理面板中添加记录时收到以下错误
TypeError at /admin/financials/balancesheet/add/
function missing required argument 'year' (pos 1)
Request Method: GET
Request URL: http://localhost:8000/admin/financials/balancesheet/add/
Django Version: 3.1
Exception Type: TypeError
Exception Value:
function missing required argument 'year' (pos 1)
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 831, in get_default
Python Executable: /usr/local/bin/python
Python Version: 3.7.8
Python Path:
['/code',
'/usr/local/lib/python37.zip',
'/usr/local/lib/python3.7',
'/usr/local/lib/python3.7/lib-dynload',
'/usr/local/lib/python3.7/site-packages']
Server time: Sun, 09 Aug 2020 11:40:48 +0000
您传递的默认值需要一个参数,这就是您收到错误的原因。如果您通过 datetime.date.today
,您可以在创建记录后将日期更改为之前的日期。
尝试替换
...
date = models.DateField(default=datetime.date)
与:
import datetime
...
date = models.DateField(default=datetime.date.today)
或者:
from datetime import datetime
...
date = models.DateField(default=datetime.now)