diff options
| author | Tom Christie | 2014-05-20 16:03:51 +0100 |
|---|---|---|
| committer | Tom Christie | 2014-05-20 16:03:51 +0100 |
| commit | 218b94e60696de649407f9292359e02e5daa787d (patch) | |
| tree | ec3704334b5ed9436e0a1cc45eb463dd1f6302e0 | |
| parent | d46d153a9979a96fae643a24286eacaf5c219401 (diff) | |
| parent | 1e7b5fd2c04e587e30cf29e15ca3074b8d33b92e (diff) | |
| download | django-rest-framework-218b94e60696de649407f9292359e02e5daa787d.tar.bz2 | |
Merge pull request #1536 from Ian-Foote/choicefield_blank_display_value
Allow customising ChoiceField blank display value
| -rw-r--r-- | docs/api-guide/fields.md | 4 | ||||
| -rw-r--r-- | rest_framework/fields.py | 8 | ||||
| -rw-r--r-- | rest_framework/tests/test_fields.py | 9 |
3 files changed, 18 insertions, 3 deletions
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 67fa65d2..58dbf977 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -184,7 +184,9 @@ Corresponds to `django.db.models.fields.SlugField`. ## ChoiceField -A field that can accept a value out of a limited set of choices. +A field that can accept a value out of a limited set of choices. Optionally takes a `blank_display_value` parameter that customizes the display value of an empty choice. + +**Signature:** `ChoiceField(choices=(), blank_display_value=None)` ## EmailField diff --git a/rest_framework/fields.py b/rest_framework/fields.py index d80aab56..2da89550 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -514,12 +514,16 @@ class ChoiceField(WritableField): 'the available choices.'), } - def __init__(self, choices=(), *args, **kwargs): + def __init__(self, choices=(), blank_display_value=None, *args, **kwargs): self.empty = kwargs.pop('empty', '') super(ChoiceField, self).__init__(*args, **kwargs) self.choices = choices if not self.required: - self.choices = BLANK_CHOICE_DASH + self.choices + if blank_display_value is None: + blank_choice = BLANK_CHOICE_DASH + else: + blank_choice = [('', blank_display_value)] + self.choices = blank_choice + self.choices def _get_choices(self): return self._choices diff --git a/rest_framework/tests/test_fields.py b/rest_framework/tests/test_fields.py index 3ae1c438..b04b947f 100644 --- a/rest_framework/tests/test_fields.py +++ b/rest_framework/tests/test_fields.py @@ -717,6 +717,15 @@ class ChoiceFieldTests(TestCase): f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES) + def test_blank_choice_display(self): + blank = 'No Preference' + f = serializers.ChoiceField( + required=False, + choices=SAMPLE_CHOICES, + blank_display_value=blank, + ) + self.assertEqual(f.choices, [('', blank)] + SAMPLE_CHOICES) + def test_invalid_choice_model(self): s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'}) self.assertFalse(s.is_valid()) |
