Search code examples
pythondjangodjango-modelsdatefield

Django use datetime.date() as input for DateField to achieve past date input


I have a simple model where I want to input a past date as the DateField in the model.

import datetime

class BalanceSheet(models.Model): 

     ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet")

     date = models.DateField(default=datetime.date)

but I receive the following error when trying to add a record in the admin panel

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

Solution

  • The default you are passing requires an argument, that is why you are getting the error. if you pass datetime.date.today you can alter the date to a previous date once the record has been created.

    Try to replace

     ...
     date = models.DateField(default=datetime.date)
    

    with:

    import datetime
    
    ...
    date = models.DateField(default=datetime.date.today)
    

    Or:

    from datetime import datetime
    
    ...    
    date = models.DateField(default=datetime.now)