diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5b28463c5..2cb729e5e 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -313,7 +313,10 @@ class RelatedField(WritableField): return value = data.get(field_name) - into[(self.source or field_name)] = self.from_native(value) + if self.blank and value is None: + into[(self.source or field_name)] = None + else: + into[(self.source or field_name)] = self.from_native(value) class ManyRelatedMixin(object): diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index 1e159a293..ac4f54ac9 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -3,7 +3,7 @@ from django.test import TestCase from rest_framework import serializers from rest_framework.tests.models import (ActionItem, Anchor, BasicModel, BlankFieldModel, BlogPost, CallableDefaultValueModel, DefaultValueModel, - ManyToManyModel, Person, ReadOnlyManyToManyModel) + ManyToManyModel, Person, ReadOnlyManyToManyModel, BlankRelatedFieldModel) class SubComment(object): @@ -525,13 +525,23 @@ class BlankFieldTests(TestCase): class BlankRelatedFieldModelTests(TestCase): def setUp(self): + class BlankInlineRelatedFieldModelSerializer(serializers.ModelSerializer): + blank_field = serializers.PrimaryKeyRelatedField(blank=True, queryset=BasicModel.objects.all()) + class Meta: + model = BlankRelatedFieldModel + class BlankRelatedFieldModelSerializer(serializers.ModelSerializer): class Meta: model = BlankRelatedFieldModel + self.inline_serializer_class = BlankInlineRelatedFieldModelSerializer self.serializer_class = BlankRelatedFieldModelSerializer self.data = {'blank_field': None} + def test_create_inline_blank_related_field(self): + serializer = self.inline_serializer_class(self.data) + self.assertEquals(serializer.is_valid(), True) + def test_create_blank_related_field(self): serializer = self.serializer_class(self.data) self.assertEquals(serializer.is_valid(), True)