From 7a408f6cd2b67fd9c4f0d3a2240dec20d2a87a7b Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Wed, 22 Feb 2017 13:06:48 +0200 Subject: [PATCH] Guard against the possible misspelling `readonly_fields` in model serializers Fixes #4897. --- rest_framework/serializers.py | 9 +++++++++ tests/test_model_serializer.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 80e384c22..94c37321f 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -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): diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index b839f56ca..cfa671125 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -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')