[Solved]-Django REST Framework: default fields in browseable API form

4👍

You actually want to set an initial value, not a default value. See the docs. Your code should be:

from django.utils import timezone


class CallSerializer(serializers.HyperlinkedModelSerializer):
    send_on = serializers.DateTimeField(initial=timezone.now())
    ...

A default value is the value provided to an attribute if no value is set for the field. The distinction between initial and default arguments mirrors the difference between Django’s initial argument for form fields and Django’s default argument for model fields.

2👍

There is a distinction between model defaults and initial values in forms. This is especially the case for default values which are actually functions because they are only called when the instance is saved. For example, which now do you want – this time at which the blank form is displayed, or the time at which the user presses “POST”? Django applies the default when saving the model if the field value is missing. To achieve what you want you need to manually set the default in the serialize field, for example:

class CallSerializer(serializers.HyperlinkedModelSerializer):
    send_on = serializers.DateTimeField(default=datetime.now)
    ...

Leave a comment