Commit 7a408f6c by Ran Benita

Guard against the possible misspelling `readonly_fields` in model serializers

Fixes #4897.
parent d82dbc09
...@@ -1290,6 +1290,15 @@ class ModelSerializer(Serializer): ...@@ -1290,6 +1290,15 @@ class ModelSerializer(Serializer):
kwargs['read_only'] = True kwargs['read_only'] = True
extra_kwargs[field_name] = kwargs 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 return extra_kwargs
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs): def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs):
......
...@@ -10,6 +10,7 @@ from __future__ import unicode_literals ...@@ -10,6 +10,7 @@ from __future__ import unicode_literals
import decimal import decimal
from collections import OrderedDict from collections import OrderedDict
import pytest
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.core.validators import ( from django.core.validators import (
MaxValueValidator, MinLengthValidator, MinValueValidator MaxValueValidator, MinLengthValidator, MinValueValidator
...@@ -1064,3 +1065,18 @@ class Issue3674Test(TestCase): ...@@ -1064,3 +1065,18 @@ class Issue3674Test(TestCase):
child_expected = {'parent': 1, 'value': 'def'} child_expected = {'parent': 1, 'value': 'def'}
self.assertEqual(child_serializer.data, child_expected) 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')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment