From ace2123d2732dbd15920eb71bcec92a9eabebfd5 Mon Sep 17 00:00:00 2001 From: Damien Nozay Date: Thu, 11 Dec 2014 14:34:45 -0800 Subject: [PATCH] Allow to subclass a Field and make it read-only Rather than subclass a `Field` and override `__init__` you may want a more data-driven approach where the defaults for `read_only`, `write_only` and `allow_null` are specified on the class. e.g. ```python class ReadOnlyLink(serializers.HyperlinkedRelatedField) read_only = True ``` --- rest_framework/fields.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index aab80982a..d3ccb6591 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -156,13 +156,27 @@ class Field(object): default_empty_html = empty initial = None - def __init__(self, read_only=False, write_only=False, + # allows to subclass a Field and have defaults on the class. + read_only = False + write_only = False + allow_null = False + + def __init__(self, read_only=None, write_only=None, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, - error_messages=None, validators=None, allow_null=False): + error_messages=None, validators=None, allow_null=None): self._creation_counter = Field._creation_counter Field._creation_counter += 1 + if read_only is None: + read_only = self.read_only + + if write_only is None: + write_only = self.write_only + + if allow_null is None: + allow_null = self.allow_null + # If `required` is unset, then use `True` unless a default is provided. if required is None: required = default is empty and not read_only