mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-05 13:00:12 +03:00
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 ```
This commit is contained in:
parent
f8e310fdbb
commit
ace2123d27
|
@ -156,13 +156,27 @@ class Field(object):
|
||||||
default_empty_html = empty
|
default_empty_html = empty
|
||||||
initial = None
|
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,
|
required=None, default=empty, initial=empty, source=None,
|
||||||
label=None, help_text=None, style=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
|
self._creation_counter = Field._creation_counter
|
||||||
Field._creation_counter += 1
|
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 unset, then use `True` unless a default is provided.
|
||||||
if required is None:
|
if required is None:
|
||||||
required = default is empty and not read_only
|
required = default is empty and not read_only
|
||||||
|
|
Loading…
Reference in New Issue
Block a user