Home > Mobile >  Prepopulate a DateTimeField in Django Rest Framework
Prepopulate a DateTimeField in Django Rest Framework

Time:01-28

I'm using a Django Rest Framework Browseable API, DateTimeField initial is not rendered

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

CodePudding user response:

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.

  • Related