File tree 3 files changed +27
-1
lines changed
3 files changed +27
-1
lines changed Original file line number Diff line number Diff line change @@ -81,7 +81,13 @@ A text string that may be used as a description of the field in HTML form fields
81
81
82
82
### ` initial `
83
83
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)
85
91
86
92
### ` style `
87
93
Original file line number Diff line number Diff line change @@ -370,6 +370,8 @@ def get_initial(self):
370
370
Return a value to use when the field is being returned as a primitive
371
371
value, without any object instance.
372
372
"""
373
+ if callable (self .initial ):
374
+ return self .initial ()
373
375
return self .initial
374
376
375
377
def get_value (self , dictionary ):
Original file line number Diff line number Diff line change @@ -191,6 +191,24 @@ def test_initial(self):
191
191
}
192
192
193
193
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
+
194
212
class TestLabel :
195
213
def setup (self ):
196
214
class TestSerializer (serializers .Serializer ):
You can’t perform that action at this time.
0 commit comments