Guard against the possible misspelling readonly_fields in model serializers

Fixes #4897.
This commit is contained in:
Ran Benita 2017-02-22 13:06:48 +02:00
parent d82dbc0925
commit 7a408f6cd2
2 changed files with 25 additions and 0 deletions

View File

@ -1290,6 +1290,15 @@ class ModelSerializer(Serializer):
kwargs['read_only'] = True
extra_kwargs[field_name] = kwargs
else:
# Guard against the possible misspelling `readonly_fields` (used
# by the Django admin and others).
assert not hasattr(self.Meta, 'readonly_fields'), (
'Serializer `%s.%s` has field `readonly_fields`; '
'the correct spelling for the option is `read_only_fields`.' %
(self.__class__.__module__, self.__class__.__name__)
)
return extra_kwargs
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs):

View File

@ -10,6 +10,7 @@ from __future__ import unicode_literals
import decimal
from collections import OrderedDict
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.validators import (
MaxValueValidator, MinLengthValidator, MinValueValidator
@ -1064,3 +1065,18 @@ class Issue3674Test(TestCase):
child_expected = {'parent': 1, 'value': 'def'}
self.assertEqual(child_serializer.data, child_expected)
class Issue4897TestCase(TestCase):
def test_should_assert_if_writing_readonly_fields(self):
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = OneFieldModel
fields = ('char_field',)
readonly_fields = fields
obj = OneFieldModel.objects.create(char_field='abc')
with pytest.raises(AssertionError) as cm:
TestSerializer(obj).fields
cm.match(r'readonly_fields')