diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 02185c2ff..163a89840 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -33,6 +33,7 @@ class RelatedField(WritableField): many_widget = widgets.SelectMultiple form_field_class = forms.ChoiceField many_form_field_class = forms.MultipleChoiceField + null_values = (None, '', 'None') cache_choices = False empty_label = None @@ -168,9 +169,9 @@ class RelatedField(WritableField): return value = [] if self.many else None - if value in (None, '') and self.required: - raise ValidationError(self.error_messages['required']) - elif value in (None, ''): + if value in self.null_values: + if self.required: + raise ValidationError(self.error_messages['required']) into[(self.source or field_name)] = None elif self.many: into[(self.source or field_name)] = [self.from_native(item) for item in value] diff --git a/rest_framework/tests/test_nullable_fields.py b/rest_framework/tests/test_nullable_fields.py index 556543d99..6ee55c005 100644 --- a/rest_framework/tests/test_nullable_fields.py +++ b/rest_framework/tests/test_nullable_fields.py @@ -15,12 +15,12 @@ urlpatterns = patterns( class NullableForeignKeyTests(APITestCase): """ - DRF should be able to handle nullable fields when a TestClient - POST/PUT request is made with its own serialized object. + DRF should be able to handle nullable foreign keys when a test + Client POST/PUT request is made with its own serialized object. """ urls = 'rest_framework.tests.test_nullable_fields' - def test_updating_object_with_null_field_value(self): + def test_updating_object_with_null_fk(self): obj = NullableForeignKeySource(name='example', target=None) obj.save() serialized_data = NullableFKSourceSerializer(obj).data