Skip to content
Advertisement

Prepopulate a DateTimeField in Django Rest Framework

I’m using a Django Rest Framework Serializer. Fields allow the initial parameter to be passed, which prepopulates a values in the browsable API. In the docs, the DateField is used as an example with an initial value of datetime.date.today.

I would like to prepopulate a DateTimeField. However, the initial value is being ignored and I see mm/dd/yyyy, --:-- -- as a default value.

import datetime

class MySerializer(serializers.Serializer):
    # DateField initial works
    my_datefield = serializers.DateField(initial=datetime.date.today)
    # DateTimeField initial does *NOT* work
    my_datetimefield = serializers.DateTimeField(initial=datetime.datetime.now)

Browseable API, DateTimeField initial is not rendered

Why is the initial value for a DateTimeField not set? How can I prepopulate the field?

Advertisement

Answer

You need to properly format your datetime object:

class MySerializer(serializers.Serializer):
    my_datetimefield = serializers.DateTimeField(
        initial=lambda: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )

In fact, the initial value is set. It just happens that an implicit cast to str() returns microseconds:

>>> import datetime
>>> now = datetime.datetime.now()
>>> str(now)
'2023-01-23 18:01:19.586632'
>>> now.strftime("%Y-%m-%d %H:%M:%S")
'2023-01-23 18:01:19'

If you have a look at the HTML, the implicitly casted string value is there: enter image description here

However, the datepicker widget can’t handle the microseconds. While the format of str(date.today()) is fine for the UI, str(datetime.now()) is not. Therefore, you need to return a string without microseconds.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement