mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-24 00:04:16 +03:00
Allow customising ChoiceField blank display value
This commit is contained in:
parent
1d404874b3
commit
6c108c459d
|
@ -509,12 +509,16 @@ class ChoiceField(WritableField):
|
||||||
'the available choices.'),
|
'the available choices.'),
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, choices=(), *args, **kwargs):
|
def __init__(self, choices=(), blank_display_value=None, *args, **kwargs):
|
||||||
self.empty = kwargs.pop('empty', '')
|
self.empty = kwargs.pop('empty', '')
|
||||||
super(ChoiceField, self).__init__(*args, **kwargs)
|
super(ChoiceField, self).__init__(*args, **kwargs)
|
||||||
self.choices = choices
|
self.choices = choices
|
||||||
if not self.required:
|
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):
|
def _get_choices(self):
|
||||||
return self._choices
|
return self._choices
|
||||||
|
|
|
@ -706,6 +706,15 @@ class ChoiceFieldTests(TestCase):
|
||||||
f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES)
|
f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES)
|
||||||
self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + 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):
|
def test_invalid_choice_model(self):
|
||||||
s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'})
|
s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'})
|
||||||
self.assertFalse(s.is_valid())
|
self.assertFalse(s.is_valid())
|
||||||
|
|
Loading…
Reference in New Issue
Block a user