mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-30 05:24:00 +03:00
Merge pull request #523 from maspwr/related-required
RelatedField should respect self.required
This commit is contained in:
commit
0576241b19
|
@ -351,7 +351,12 @@ class RelatedField(WritableField):
|
||||||
if self.read_only:
|
if self.read_only:
|
||||||
return
|
return
|
||||||
|
|
||||||
value = data.get(field_name)
|
try:
|
||||||
|
value = data[field_name]
|
||||||
|
except KeyError:
|
||||||
|
if self.required:
|
||||||
|
raise ValidationError(self.error_messages['required'])
|
||||||
|
return
|
||||||
|
|
||||||
if value in (None, '') and not self.null:
|
if value in (None, '') and not self.null:
|
||||||
raise ValidationError('Value may not be null')
|
raise ValidationError('Value may not be null')
|
||||||
|
|
|
@ -308,6 +308,38 @@ class ModelValidationTests(TestCase):
|
||||||
self.assertFalse(second_serializer.is_valid())
|
self.assertFalse(second_serializer.is_valid())
|
||||||
self.assertEqual(second_serializer.errors, {'title': [u'Album with this Title already exists.']})
|
self.assertEqual(second_serializer.errors, {'title': [u'Album with this Title already exists.']})
|
||||||
|
|
||||||
|
def test_foreign_key_with_partial(self):
|
||||||
|
"""
|
||||||
|
Test ModelSerializer validation with partial=True
|
||||||
|
|
||||||
|
Specifically test foreign key validation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
album = Album(title='test')
|
||||||
|
album.save()
|
||||||
|
|
||||||
|
class PhotoSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Photo
|
||||||
|
|
||||||
|
photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk})
|
||||||
|
self.assertTrue(photo_serializer.is_valid())
|
||||||
|
photo = photo_serializer.save()
|
||||||
|
|
||||||
|
# Updating only the album (foreign key)
|
||||||
|
photo_serializer = PhotoSerializer(instance=photo, data={'album': album.pk}, partial=True)
|
||||||
|
self.assertTrue(photo_serializer.is_valid())
|
||||||
|
self.assertTrue(photo_serializer.save())
|
||||||
|
|
||||||
|
# Updating only the description
|
||||||
|
photo_serializer = PhotoSerializer(instance=photo,
|
||||||
|
data={'description': 'new'},
|
||||||
|
partial=True)
|
||||||
|
|
||||||
|
self.assertTrue(photo_serializer.is_valid())
|
||||||
|
self.assertTrue(photo_serializer.save())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class RegexValidationTest(TestCase):
|
class RegexValidationTest(TestCase):
|
||||||
def test_create_failed(self):
|
def test_create_failed(self):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user