mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-03 21:24:33 +03:00
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`
This commit is contained in:
commit
0b6f53eb98
|
@ -81,7 +81,13 @@ A text string that may be used as a description of the field in HTML form fields
|
|||
|
||||
### `initial`
|
||||
|
||||
A value that should be used for pre-populating the value of HTML form fields.
|
||||
A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
|
||||
you may do with any regular Django `Field`:
|
||||
|
||||
import datetime
|
||||
from rest_framework import serializers
|
||||
class ExampleSerializer(serializers.Serializer):
|
||||
day = serializers.DateField(initial=datetime.date.today)
|
||||
|
||||
### `style`
|
||||
|
||||
|
|
|
@ -370,6 +370,8 @@ class Field(object):
|
|||
Return a value to use when the field is being returned as a primitive
|
||||
value, without any object instance.
|
||||
"""
|
||||
if callable(self.initial):
|
||||
return self.initial()
|
||||
return self.initial
|
||||
|
||||
def get_value(self, dictionary):
|
||||
|
|
|
@ -191,6 +191,24 @@ class TestInitial:
|
|||
}
|
||||
|
||||
|
||||
class TestInitialWithCallable:
|
||||
def setup(self):
|
||||
def initial_value():
|
||||
return 123
|
||||
|
||||
class TestSerializer(serializers.Serializer):
|
||||
initial_field = serializers.IntegerField(initial=initial_value)
|
||||
self.serializer = TestSerializer()
|
||||
|
||||
def test_initial_should_accept_callable(self):
|
||||
"""
|
||||
Follows the default ``Field.initial`` behaviour where they accept a
|
||||
callable to produce the initial value"""
|
||||
assert self.serializer.data == {
|
||||
'initial_field': 123,
|
||||
}
|
||||
|
||||
|
||||
class TestLabel:
|
||||
def setup(self):
|
||||
class TestSerializer(serializers.Serializer):
|
||||
|
|
Loading…
Reference in New Issue
Block a user