Skip to content

Commit 0b6f53e

Browse files
committed
Merge pull request #3943 from erickwilder/3937-accept-callable-as-initial-value
Closes #3937. Support callable as the value of `initial` for any `serializer.Field`
2 parents 5ace717 + a32baea commit 0b6f53e

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

docs/api-guide/fields.md

+7-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,13 @@ A text string that may be used as a description of the field in HTML form fields
8181

8282
### `initial`
8383

84-
A value that should be used for pre-populating the value of HTML form fields.
84+
A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
85+
you may do with any regular Django `Field`:
86+
87+
import datetime
88+
from rest_framework import serializers
89+
class ExampleSerializer(serializers.Serializer):
90+
day = serializers.DateField(initial=datetime.date.today)
8591

8692
### `style`
8793

rest_framework/fields.py

+2
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,8 @@ def get_initial(self):
370370
Return a value to use when the field is being returned as a primitive
371371
value, without any object instance.
372372
"""
373+
if callable(self.initial):
374+
return self.initial()
373375
return self.initial
374376

375377
def get_value(self, dictionary):

tests/test_fields.py

+18
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,24 @@ def test_initial(self):
191191
}
192192

193193

194+
class TestInitialWithCallable:
195+
def setup(self):
196+
def initial_value():
197+
return 123
198+
199+
class TestSerializer(serializers.Serializer):
200+
initial_field = serializers.IntegerField(initial=initial_value)
201+
self.serializer = TestSerializer()
202+
203+
def test_initial_should_accept_callable(self):
204+
"""
205+
Follows the default ``Field.initial`` behaviour where they accept a
206+
callable to produce the initial value"""
207+
assert self.serializer.data == {
208+
'initial_field': 123,
209+
}
210+
211+
194212
class TestLabel:
195213
def setup(self):
196214
class TestSerializer(serializers.Serializer):

0 commit comments

Comments
 (0)