From afe7ed9333e37384f8ddc57e891da9632c8714c3 Mon Sep 17 00:00:00 2001
From: José Padilla
Date: Tue, 9 Dec 2014 09:25:06 -0400
Subject: Add allow_blank for ChoiceField #2184
This makes a ChoiceField optional in HTML if
model field has `blank=True` set.---
rest_framework/fields.py | 5 +++++
rest_framework/serializers.py | 2 +-
.../templates/rest_framework/horizontal/select.html | 2 +-
rest_framework/templates/rest_framework/inline/select.html | 2 +-
rest_framework/templates/rest_framework/vertical/select.html | 2 +-
rest_framework/utils/field_mapping.py | 12 ++++++------
6 files changed, 15 insertions(+), 10 deletions(-)
(limited to 'rest_framework')
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
index 0c6c2d39..99498da7 100644
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -958,9 +958,14 @@ class ChoiceField(Field):
(six.text_type(key), key) for key in self.choices.keys()
])
+ self.allow_blank = kwargs.pop('allow_blank', False)
+
super(ChoiceField, self).__init__(**kwargs)
def to_internal_value(self, data):
+ if data == '' and self.allow_blank:
+ return ''
+
try:
return self.choice_strings_to_values[six.text_type(data)]
except KeyError:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
index fb6c826b..b0c0efa7 100644
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -942,7 +942,7 @@ class ModelSerializer(Serializer):
# `ModelField`, which is used when no other typed field
# matched to the model field.
kwargs.pop('model_field', None)
- if not issubclass(field_cls, CharField):
+ if not issubclass(field_cls, CharField) and not issubclass(field_cls, ChoiceField):
# `allow_blank` is only valid for textual fields.
kwargs.pop('allow_blank', None)
diff --git a/rest_framework/templates/rest_framework/horizontal/select.html b/rest_framework/templates/rest_framework/horizontal/select.html
index 380b38e9..8a7fca37 100644
--- a/rest_framework/templates/rest_framework/horizontal/select.html
+++ b/rest_framework/templates/rest_framework/horizontal/select.html
@@ -4,7 +4,7 @@
{% endif %}